C#: DataTable to CSV

 

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.

(more…)

Shares