Language: EN

csv-helper

How to work with CSV in C# with CsvHelper

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

At this point in the game Saying that a CSV file is not the best way to store data is nothing new. But not all program developers may be 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 serialization and deserialization of objects to CSV. It also automatically handles data type detection and syntactic parsing of CSV strings.

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

In short, it has all the functionality you will need to work with CSV files. This is why it is one of the most popular libraries for performing 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, let’s say we have a class, for example

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

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

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

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

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);
}

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

As is usual in this type of libraries, it has various options. Especially for column mapping and type conversion. Consult the library’s documentation for more information.

CsvHelper is Open Source, and all the code and documentation is available on the project page https://joshclose.github.io/CsvHelper/ and in the repository https://github.com/JoshClose/CsvHelper