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

Leave a Reply

Your email address will not be published.

I accept that my given data and my IP address is sent to a server in the USA only for the purpose of spam prevention through the Akismet program.More information on Akismet and GDPR.