DataTable to CSV

This might come in handy for anyone who wishes to get there data from a DataTable into CSV format:

public static class DataTableExtensions
{
    public static string ToCsv(this DataTable dt)
    {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < dt.Columns.Count; i++)
        {
            sb.Append(dt.Columns[i].ColumnName);
            if (i < dt.Columns.Count - 1) 
                sb.Append(",");
        }
        sb.Append(Environment.NewLine);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                sb.Append("\"");
                var row = dt.Rows[i][j].ToString().Replace("\"", "\"\"");
                sb.Append(row);
                sb.Append("\"");
                if (j < dt.Columns.Count - 1) 
                    sb.Append(",");
            }
            sb.Append(Environment.NewLine);
        }
        
        return sb.ToString();
    }
}

I have kept it simple by always wrapping the row values inside double quotes therefore should handle special characters ok, and I was in two minds whether to have this as a decorator around a DataTable or to just extend DataTable via extension method as you can see I went for the latter, not sure it matters much either way.

Advertisements