Borrowing from c# datatable to csv as mentioned, I would create an extension method that takes two format strings as parameters and looks like this:
static class MyExtensions
{
public static string ToCSV(this DataTable dataTable, string rowFormat, string headFormat)
{
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = dataTable.Columns.Cast<DataColumn>().
Select(column => column.ColumnName);
sb.AppendFormat(headFormat, columnNames.ToArray<string>());
foreach (DataRow row in dataTable.Rows)
{
sb.AppendLine();
sb.AppendFormat(rowFormat, row.ItemArray);
}
return sb.ToString();
}
}
Then call it like this:
using (DataTable dt = new DataTable("Test"))
{
dt.Columns.Add(new DataColumn("id", typeof(int)));
dt.Columns.Add(new DataColumn("value", typeof(double)));
dt.Columns.Add(new DataColumn("dated", typeof(DateTime)));
dt.Rows.Add(new Object[] { 1, 2.3, DateTime.Now });
Console.WriteLine(dt.ToCSV("{0}|\"{1}\"|{2:d}", "{0}|{1}|{2}"));
Console.ReadKey();
}
To produce this:
id|value|dated
1|"2.3"|04/10/2016
This gives you the flexibility to define the structure of your CSV precisely.
If you don't know the structure, then this won't help.