C# save DataTable to CSV easily
I find I need to save C# DataTables to CSV files often and as such use the following code:
public static void SaveToCsv(this DataTable data, string fileName)
{
using (var messageSave = new StreamWriter(fileName))
{
foreach (DataColumn col in data.Columns)
{
if (col.ColumnName.Contains("\""))
messageSave.Write($"\"{col.ColumnName}\",");
else
messageSave.Write($"{col.ColumnName},");
}
messageSave.Write(Environment.NewLine);
foreach (DataRow row in data.Rows)
{
foreach (object s in row.ItemArray)
{
if (s.ToString().Contains("\""))
messageSave.Write($"\"{s.ToString()}\",");
else
messageSave.Write($"{s.ToString()},");
}
messageSave.Write(Environment.NewLine);
}
}
}