Recently I wrote a small program to allow me to connect to a SQL database and export a selected table to a CSV file. So I needed a method that can take in a DataTable and the delimiter character to use. The returned result is a string which can be save straight to a text file.
Below is the method in my program, you may copy, modify and use it in your own program.
I use a StringBuilder class to build my lines of comma separated values and then return it as a String type. Currently the code only format string values with double quotes inserted around the value and the rest is a straight output.
private string ToDelimited(DataTable table, string delimiter) { StringBuilder strBuilder = new StringBuilder(); string line = string.Empty; foreach (DataColumn col in table.Columns) { line += col.ColumnName; if (table.Columns.IndexOf(col) + 1 < table.Columns.Count) { line += ","; } } strBuilder.AppendLine(line); foreach (DataRow row in table.Rows) { line = string.Join(delimiter, Array.ConvertAll<object, string> (row.ItemArray, delegate(object obj) { if (obj is string) { return string.Format("\"{0}\"", obj as string); } else { return obj.ToString(); } })); strBuilder.AppendLine(line); } return strBuilder.ToString(); }