csv-helper

How to work with CSV in C# with CsvHelper

  • 2 min

CsvHelper is a C# library that makes it easy to read and write CSV files in .NET applications.

At this point in the story, saying that a CSV file is not the best way to store data is nothing new. But not all software developers are aware of this, so from time to time, we will have to deal with them.

When you have “that luck” (wink wink) of having to work with CSV files from a .NET application, CsvHelper will be your best friend.

CsvHelper allows the serialization and deserialization of objects to CSV. Additionally, it automatically handles data type detection and CSV string parsing.

It is also compatible with anonymous types and DataReader, as well as LINQ to facilitate search operations and data filtering.

In short, it has all the functionalities you will need to work with CSV files. This is why it is one of the most popular libraries for this task.

How to Use CsvHelper

We can easily add the library to a .NET project through the corresponding Nuget package.

Install-Package CsvHelper

Now, suppose we have a class, for example

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}
Copied!

In this case, reading a CSV file would be this simple,

using (var reader = new StreamReader("path_to_your_csv.csv"))

using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
    var records = csv.GetRecords<Person>();
}
Copied!

While writing would be,

var Person = new List<Person>
{
    new Person { Id = 1, Name = "Adam", Age = 39 },
};

using (var writer = new StreamWriter("path_to_your_csv.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    csv.WriteRecords(records);
}
Copied!

The library is compatible with anonymous types, and even dynamic types. It also provides a method to load them as a DataTable, although the author himself says he finds its use unnecessary (I agree),

As is usual with this type of library, it has various options. Especially for column mapping and type conversion. Check the library documentation for more information.