Could somebody please tell me why the following code is not working. The data is saved into the csv file, however the data is not separated. It all exists within the first cell of each row.
StringBuilder sb = new StringBuilder();
foreach (DataColumn col in dt.Columns)
{
sb.Append(col.ColumnName + ',');
}
sb.Remove(sb.Length - 1, 1);
sb.Append(Environment.NewLine);
foreach (DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
sb.Append(row[i].ToString() + ",");
}
sb.Append(Environment.NewLine);
}
File.WriteAllText("test.csv", sb.ToString());
Thanks.
4 lines of code:
Note that the
ToList()
at the end is important; I need something to force an expression evaluation. If I was code golfing, I could useMin()
instead.Also note that the result will have a newline at the end because of the last call to
AppendLine()
. You may not want this. You can simply callTrimEnd()
to remove it.I wrapped this up into an extension class, which allows you to call:
on any DataTable.
Read this and this?
A better implementation would be
To write to a file, I think the following method is the most efficient and straightforward: (You can add quotes if you want)