CSV Writing Intro

Here we cover the basics of writing CSV files in C#. This is also useful when you only read CSV files from 3rd parties. For example, for unit testing.

To write a CSV file using CSVHelper in C#, we first need to define the CSV field mappings in a class file in C#. We will reuse the definition from the CSV Parsing Intro. See this article for details.

Next, we can define a function to write to a CSV file using CsvWriter:

public async Task WriteCsvFile(IEnumerable<CsvRecord> records, FileInfo fileInfo) {
    Logger.LogInformation($"Writing file to {fileInfo.FullName}");
    await using var writer = new StreamWriter(fileInfo.FullName);
    await using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
    // make a new line
    await csv.NextRecordAsync();
    await csv.WriteRecordsAsync(records);

We have covered CsvConfiguration options for reading, where they are most useful. For writing, some options that might be useful are

  • IncludePrivateMembers — boolean to define whether private members of the class should be written to csv.

Unfortunately, I found that datetime format annotations do not have an effect when writing CSV file. To write Dates/DateTimes in a desired format, you can apply special converter options before writing the file:

var options = new TypeConverterOptions { Formats = new [] { "MM/dd/yyyy" } };