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

解决方案 »

  1.   

    遍历数据,使用以下方式写到文件中
      /// <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; }
            }
      

  2.   

    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();
                }
      

  3.   

    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["字段"]+","+字段);  
                               }  
    }