【发布时间】:2012-06-09 09:49:19
【问题描述】:
这是我第一次对平面文件进行任何类型的工作。 我需要这是一个纯 txt 文件而不是 XML。
我写了以下选择逗号分隔的格式。
public static void DataTableToFile(string fileLoc, DataTable dt)
{
StringBuilder str = new StringBuilder();
// get the column headers
foreach (DataColumn c in dt.Columns)
{
str.Append(c.ColumnName.ToString() + ",");
}
str.Remove(str.Length-1, 1);
str.AppendLine();
// write the data here
foreach (DataRow dr in dt.Rows)
{
foreach (var field in dr.ItemArray)
{
str.Append(field.ToString() + ",");
}
str.Remove(str.Length-1, 1);
str.AppendLine();
}
try
{
Write(fileLoc, str.ToString());
}
catch (Exception ex)
{
//ToDO:Add error logging
}
}
我的问题是:我可以做得更好或更快吗?
str.Remove(str.Length-1, 1); 可以删除最后一个 ,,这是我能想到的唯一方法。
有什么建议吗?
【问题讨论】:
-
您实际上是在尝试将数据表写入 CSV 格式。见stackoverflow.com/questions/4959722/c-sharp-datatable-to-csv
标签: c#