C# and SQL Server – Exporting Data (CSV)

Sometimes it can be useful to export data from a database, so that it can be analysed, or, to import in to another computer system. CSV, or Comma Separated Value files, are one such file format that allows for both of these scenarios.

Below is an example of how C# can be used to export data to a CSV file called ‘personexport.csv’, from an SQL Server database table called ‘person’, which was used in the examples for selectinginserting, updating, deleting and importing data (CSV, text, XML and JSON).

Firstly, a connection to the database is established, the CSV file path and name are set and a check is made to see if the path actually exists. If it does, a query is executed to extract the data from the database and the CSV file is opened for writing. The table headers are then added to the CSV file, followed by the rows of data, one by one.

A rolling seven day backup is also included. This makes a copy of the CSV file that has just been created, giving it a name that includes the index number for the day of the week, along with the day itself, for example, 'personexport-1-monday.csv', for the backup on a Monday. Here, Sunday is classed as the first day of the week, with an index value of zero. Note that the backup is only done for the first time that this is run in a given day. Backups are then overwritten each week.

Finally, confirmation of a successful export is provided. A ‘try-catch-finally’ block is used to catch any errors that may occur, as well as tidy up at the end, regardless of whether the export is successful or not.

// Database connection variable.
SqlConnection connect = new SqlConnection(
    "Server=MSSQLSERVERDEMO; Database=Demo;" +
    "User Id=DemoUN; Password=DemoPW");


    // Connect to database.

catch (Exception e)

    // Confirm unsuccessful connection and stop program execution.
    Console.WriteLine("Database connection unsuccessful.");


// Export path and file.
string exportPath = @"C:\demo\";
string exportCsv = "personexport.csv";

// Stream writer for CSV file.
StreamWriter csvFile = null;

// Check to see if the file path exists.
if (!Directory.Exists(exportPath))

    // Display a message stating file path does not exist.
    Console.WriteLine("File path does not exist.");

    // Stop program execution.



    // Query text.
    string sqlText = @"
        SELECT id, firstname, lastname, title, dob 
        FROM dbo.person 
        ORDER BY id

    // Query text incorporated into SQL command.
    SqlCommand sqlSelect = new SqlCommand(sqlText, connect);

    // Execute SQL and place data in a reader object.
    SqlDataReader reader = sqlSelect.ExecuteReader();

    // Stream writer for CSV file.
    csvFile = new StreamWriter(@exportPath + exportCsv);

    // Add the headers to the CSV file.
    csvFile.WriteLine(String.Format("\"{0}\",\"{1}\",\"{2}\"," +
        reader.GetName(0), reader.GetName(1), reader.GetName(2), 
        reader.GetName(3), reader.GetName(4)));

    // Construct CSV file data rows.
    while (reader.Read())

        // Add line from reader object to new CSV file.
        csvFile.WriteLine(String.Format("\"{0}\",\"{1}\",\"{2}\"," +
            reader[0], reader[1], reader[2], reader[3], reader[4]));


    // Close the file.

    // Today's date.
    DateTime today = DateTime.Now;

    // Construct the backup file name.
    string exportBackupCsv = exportCsv.Substring(0, exportCsv.Length-4) +
        "-" + (int)today.DayOfWeek + "-" +
        today.DayOfWeek.ToString().ToLower() + ".csv";

    // Check if the backup file does not exist, or if it does, check that
    // today's date is different from the last modified date.
    if (!File.Exists(Path.Combine(exportPath, exportBackupCsv)) || 
        (File.Exists(Path.Combine(exportPath, exportBackupCsv)) && 
            Path.Combine(exportPath, exportBackupCsv)).Date != 

        // Copy the CSV export.
        File.Copy(Path.Combine(exportPath, exportCsv),
            Path.Combine(exportPath, exportBackupCsv), true);


    // Message stating export successful.
    Console.WriteLine("Data export successful.");

catch (Exception e)

    // Message stating export unsuccessful.
    Console.WriteLine("Data export unsuccessful.");


    // Close the database connection and CSV file.


The CSV file produced contains the following data. Note that, although dates in an SQL Server database are stored in the format YYYY-MM-DD (four digit year, two digit month and two digit day), they are output to CSV in a day, month, year and time format.

"1","Bob","Smith","Mr","20/01/1980 00:00:00"
"3","Fred","Bloggs","Mr","07/05/1975 00:00:00"
"4","Alan","White","Mr","20/03/1989 00:00:00"
"5","Fiona","Bloggs","Mrs","19/05/1985 00:00:00"
"6","Zoe","Davis","Miss","11/07/1979 00:00:00"
"7","Tom","Ingram","Mr","04/10/1971 00:00:00"
"8","Karen","Thomas","Mrs","08/03/1969 00:00:00"
"9","Samantha","Yates","Miss","27/08/1995 00:00:00"

Further Resources