C#: DataTable to Csv String
Author: jason
Date: 2019-01-19 15:42:09
Category: Technical

Often I need to send a DataTable out as a CSV. And I need the fields wrapped in quotes. Here is some code I ran across that makes that task very easy. A use case would be getting data right out of the database and sending as a CSV string to the end user, write it out to a file or whatever.

Code


public static string WrapInQuotes(string s)
{
return String.Format(""{0}"", s);
}

public static void SendDataTableAsCsvString()
{
//using System.Data; using System.Linq; using System.Text;
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Description");
dt.Rows.Add(new object[] { "Apple", "Red" });
dt.Rows.Add(new object[] { "Pear", null });

var builder = new StringBuilder();
var columnNames = dt.Columns.Cast().Select(column => WrapInQuotes(column.ColumnName));
builder.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dt.Rows)
{
var fields = row.ItemArray.Select(field => WrapInQuotes(field.ToString()));
builder.AppendLine(string.Join(",", fields));
}

Console.Write(builder.ToString());
}







jason @ jasonthomasfrance.com - www.masterstationlog.com - copyright 2009