将数据从DataTable写入文本文件

public void GenerateDetailFile() { if (!Directory.Exists(AppVars.IntegrationFilesLocation)) { Directory.CreateDirectory(AppVars.IntegrationFilesLocation); } DateTime DateTime = DateTime.Now; using (StreamWriter sw = File.CreateText(AppVars.IntegrationFilesLocation + DateTime.ToString(DateFormat) + " Detail.txt")) { DataTable table = Database.GetDetailTXTFileData(); foreach (DataRow row in table.Rows) { sw.WriteLine(row); } } } 

不知道我在这里缺少什么,但我认为它可能是列名,我不知道如何设置它。

这工作正常,除了当它写入文本文件时,它正在编写:

的System.Data.DataRow
的System.Data.DataRow
的System.Data.DataRow
的System.Data.DataRow
的System.Data.DataRow
的System.Data.DataRow
的System.Data.DataRow
的System.Data.DataRow
的System.Data.DataRow
的System.Data.DataRow

任何人都可以帮我一把吗?

就像是:

 sw.WriteLine(row["columnname"].ToString()); 

会更合适。

当您尝试打印出类似的DataRow ,它调用的是Object.ToString() ,它只打印出该类型的名称。 你想要做的是:

 sw.WriteLine(String.Join(",", row.ItemArray)); 

这将打印DataRow中所有项目的逗号分隔列表。

下面的代码将让你写出文本文件,每列用’|’分隔

  foreach (DataRow row in dt.Rows) { object[] array = row.ItemArray; for (i = 0; i < array.Length - 1; i++) { swExtLogFile.Write(array[i].ToString() + " | "); } swExtLogFile.WriteLine(array[i].ToString()); } 

参考链接

DataRow没有“自然”字符串表示。 您需要以您想要的任何格式编写它,即以逗号分隔的值列表等。您可以枚举列并打印它们的值,例如:

 foreach (DataRow row in table.Rows) { bool firstCol = true; foreach (DataColumn col in table.Columns) { if (!firstCol) sw.Write(", "); sw.Write(row[col].ToString()); firstCol = false; } sw.WriteLine(); } 

您需要从每个DataRow写入列。 目前您正在编写DataRow对象,即dataRow.ToString(),因此您在文件中获得dataRow的字符串名称"System.Data.DataRow"

 foreach(DataRow row in table.Rows) { foreach(DataColumn column in table.Columns) { sw.WriteLine(row[column]); } }