日期:2014-05-17  浏览次数:21181 次

c#中将sqlite数据库查询的结果,写入到txt文件
我将查询结果绑定到了DataSet ds
怎么写入到txt呢,保证每条数据之间用逗号隔开,如下
日期,性别,科目,分数//这一行题目也得写上
20110101,男,语文,98
20110102,女,数学,95

------解决方案--------------------
遍历数据,使用以下方式写到文件中

C# code

  /// <summary>
        /// 追加内容到文件
        /// 不存在此文件自动创建
        /// </summary>
        /// <param name="pathandname">文件全路径</param>
        /// <param name="msg">内容</param>
        public static void AppendTextToFile(string pathandname, string msg)
        {
            try
            {
                using (System.IO.StreamWriter sw = System.IO.File.AppendText(pathandname))
                {
                    sw.WriteLine(msg);
                    sw.Dispose();
                }
            }
            catch (Exception ex) { throw ex; }
        }

------解决方案--------------------
C# code
DataTable dt = ds.Tables[0];
            using (StreamWriter sw = new StreamWriter("路径"))
            {
                bool isFirst = true;
                foreach (DataColumn column in dt.Columns)
                {
                    if (!isFirst)
                    {
                        sw.Write(",");
                    }
                    isFirst = false;
                    sw.Write(column.ColumnName);
                }
                foreach (DataRow row in dt.Rows)
                {
                    foreach (DataColumn column in dt.Columns)
                    {
                        if (!isFirst)
                        {
                            sw.Write(",");
                        }
                        isFirst = false;
                        sw.Write(row[column.ColumnName]);
                    }
                }
                sw.Flush();
                sw.Close();
            }

------解决方案--------------------
for(int i=0;i<ds.tables.count;i++){
FileStream fs;
fs = File.Create(@"D:/test1.txt");//创建不要用file创建
fs.Close();
using (StreamWriter sw = File.AppendText(@"D:/test1.txt"))
{
sw.WriteLine(ds.tables["字段"]+","+字段);
}
}