Skip to content

Instantly share code, notes, and snippets.

@SamWM
Created June 14, 2010 16:23
Show Gist options
  • Select an option

  • Save SamWM/437902 to your computer and use it in GitHub Desktop.

Select an option

Save SamWM/437902 to your computer and use it in GitHub Desktop.
Extension Methods for Generating CSV strings from objects (C# 3.0)
using System;
public static class CSVExtensions
{
public static string ToCSV(this DataTable dt)
{
string output = string.Empty;
string tmp;
char[] special = new char[] { '"', '\n', '\r', ',' };
// loop through all columns
for (int i = 0; i < dt.Columns.Count; i++)
{
output += "\"" + dt.Columns[i].ColumnName + "\"";
// if last column, add \r\n, otherwise ,
output += (dt.Columns.Count == (i + 1)) ? "\r\n" : ",";
}
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
tmp = dr[i].ToString();
// if there are any special characters, wrap in "
if (tmp.IndexOfAny(special) > 0)
{
// replace " with ""
// replace \r\n or \r with \n
tmp = tmp.Replace("\"", "\"\"").Replace("\r\n", "\n").Replace('\r', '\n');
tmp = "\"" + tmp + "\"";
}
output += tmp;
// if last column, add \r\n, otherwise ,
output += (dt.Columns.Count == (i + 1)) ? "\r\n" : ",";
}
}
return output;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment