C# Write CSV files

Summary: in this tutorial, you’ll learn how to use the CsvHelper library to write data into a CSV file from a C# program.

This tutorial assumes that you have a quick overview of the CsvHelper library and already install it in your project. If this is not the case, you can follow the reading from a CSV file tutorial first.

Writing data into a CSV file

The following example demonstrates how to use the CsvHelper library to write data into a CSV file:

using CsvHelper;
using CsvHelper.Configuration.Attributes;
using System.Globalization;


class Employee
{
    [Name("First Name")]
    public string? FirstName { get; set; }

    [Name("Last Name")]
    public string? LastName { get; set; }

    [Name("Joined Date")]
    public DateOnly? JoinedDate { get; set; }

    [Name("Salary")]
    public decimal? Salary { get; set; }

    [Name("Active")]
    public string? Active { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var employees = new List<Employee> {
           new Employee {
              FirstName = "John", LastName = "Doe", JoinedDate = new DateOnly(2020, 1, 1), Salary = 50000.00M, Active = "Yes"
           },
           new Employee {
              FirstName = "Jane", LastName = "Doe", JoinedDate = new DateOnly(2021, 6, 15), Salary = 60000.00M, Active = "Yes"
           },
           new Employee {
              FirstName = "Bob", LastName = "Smith", JoinedDate = new DateOnly(2019, 3, 10), Salary = 70000.00M, Active = "No"
           }
        };


        using var writer = new StreamWriter("output.csv");
        using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);


        csv.WriteHeader<Employee>();
        csv.NextRecord();
        foreach (var employee in employees)
        {
            csv.WriteRecord(employee);
            csv.NextRecord();
        }

    }
}Code language: C# (cs)

The contents of the output.csv file will look like this:

First Name,Last Name,Joined Date,Salary,Active
John,Doe,01/01/2020,50000.00,Yes
Jane,Doe,06/15/2021,60000.00,Yes
Bob,Smith,03/10/2019,70000.00,No
Code language: plaintext (plaintext)

How it works.

First, define the Employee class that has properties for first name, last name, joined date, salary, and active status:

class Employee
{
    [Name("First Name")]
    public string? FirstName { get; set; }

    [Name("Last Name")]
    public string? LastName { get; set; }

    [Name("Joined Date")]
    public DateOnly? JoinedDate { get; set; }

    [Name("Salary")]
    public decimal? Salary { get; set; }

    [Name("Active")]
    public string? Active { get; set; }
}Code language: C# (cs)

Notice that we mark these properties with the Name attribute, which specifies the column names of the output CSV files.

Next, create a List of Employee objects and initialize it with some sample data in the Main() method of the Program class:

var employees = new List<Employee> {
   new Employee {
      FirstName = "John", LastName = "Doe", JoinedDate = new DateOnly(2020, 1, 1), Salary = 50000.00M, Active = "Yes"
   },
   new Employee {
      FirstName = "Jane", LastName = "Doe", JoinedDate = new DateOnly(2021, 6, 15), Salary = 60000.00M, Active = "Yes"
   },
   new Employee {
      FirstName = "Bob", LastName = "Smith", JoinedDate = new DateOnly(2019, 3, 10), Salary = 70000.00M, Active = "No"
   }
};Code language: C# (cs)

Then, create a StreamWriter object to write to a CSV file named “output.csv“. Also, create a CsvWriter object, which writes the data to the CSV file:

using var writer = new StreamWriter("output.csv");
using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);Code language: C# (cs)

We configure the CsvWriter object with the InvariantCulture, which formats the output consistently regardless of the user’s cultural settings.

After that, write the header row to the CSV file by calling the WriteHeader() method of the CsvWriter object.

csv.WriteHeader<Employee>();Code language: C# (cs)

Then, call the NextRecord() method to move to the next row:

csv.NextRecord();Code language: C# (cs)

Finally, iterate through each Employee object in the list, calls the WriteRecord method of the CsvWriter object to write the employee data to the current row, and call the NextRecord method to move to the next row:

foreach (var employee in employees)
{
    csv.WriteRecord(employee);
    csv.NextRecord();
}Code language: C# (cs)

Summary

  • Use the CsvHelper library to write data into a CSV file.
Was this tutorial helpful ?