Reading a CSV file in .NET?

Viewed 105734

How do I read a CSV file using C#?

12 Answers

You could try CsvHelper, which is a project I work on. Its goal is to make reading and writing CSV files as easy as possible, while being very fast.

Here are a few ways you can read from a CSV file.

// By type
var records = csv.GetRecords<MyClass>();
var records = csv.GetRecords( typeof( MyClass ) );

// Dynamic
var records = csv.GetRecords<dynamic>();

// Using anonymous type for the class definition
var anonymousTypeDefinition =
{
    Id = default( int ),
    Name = string.Empty,
    MyClass = new MyClass()
};
var records = csv.GetRecords( anonymousTypeDefinition );

I have been maintaining an open source project called FlatFiles for several years now. It's available for .NET Core and .NET 4.5.1.

Unlike most of the alternatives, it allows you to define a schema (similar to the way EF code-first works) with an extreme level of precision, so you aren't fight conversion issues all the time. You can map directly to your data classes, and there is also support for interfacing with older ADO.NET classes.

Performance-wise, it's been tuned to be one of the fastest parsers for .NET, with a plethora of options for quirky format differences. There's also support for fixed-length files, if you need it.

You can try Cinchoo ETL - an open source lib for reading and writing CSV files.

Couple of ways you can read CSV files

Id, Name
1, Tom
2, Mark

This is how you can use this library to read it

using (var reader = new ChoCSVReader("emp.csv").WithFirstLineHeader())
{
   foreach (dynamic item in reader)
   {
      Console.WriteLine(item.Id);
      Console.WriteLine(item.Name);
   }
}

If you have POCO object defined to match up with CSV file like below

public class Employee
{
   public int Id { get; set; }
   public string Name { get; set; }
}

You can parse the same file using this POCO class as below

using (var reader = new ChoCSVReader<Employee>("emp.csv").WithFirstLineHeader())
{
   foreach (var item in reader)
   {
      Console.WriteLine(item.Id);
      Console.WriteLine(item.Name);
   }
}

Please check out articles at CodeProject on how to use it.

Disclaimer: I'm the author of this library

you can use this library: Sky.Data.Csv https://www.nuget.org/packages/Sky.Data.Csv/ this is a really fast CSV reader library and it's really easy to use:

using Sky.Data.Csv;

var readerSettings = new CsvReaderSettings{Encoding = Encoding.UTF8};
using(var reader = CsvReader.Create("path-to-file", readerSettings)){
    foreach(var row in reader){
        //do something with the data
    }
}

it also supports reading typed objects with CsvReader<T> class which has a same interface.

Related