Is there a default/official/recommended way to parse CSV files in C#? I don't want to roll my own parser.
Also, I've seen instances of people using ODBC/OLE DB to read CSV via the Text driver, and a lot of people discourage this due to its "drawbacks." What are these drawbacks?
Ideally, I'm looking for a way through which I can read the CSV by column name, using the first record as the header / field names. Some of the answers given are correct but work to basically deserialize the file into classes.
This code reads csv to DataTable:
CsvHelper (a library I maintain) will read a CSV file into custom objects.
Sometimes you don't own the objects you're trying to read into. In this case, you can use fluent mapping because you can't put attributes on the class.
Another one to this list, Cinchoo ETL - an open source library to read and write multiple file formats (CSV, flat file, Xml, JSON etc)
Sample below shows how to read CSV file quickly (No POCO object required)
Sample below shows how to read CSV file using POCO object
Please check out articles at CodeProject on how to use it.
This solution is using the official Microsoft.VisualBasic assembly to parse CSV.
Advantages:
Code:
I know its a bit late but just found a library
Microsoft.VisualBasic.FileIO
which hasTextFieldParser
class to process csv files.I have written TinyCsvParser for .NET, which is one of the fastest .NET parsers around and highly configurable to parse almost any CSV format.
It is released under MIT License:
You can use NuGet to install it. Run the following command in the Package Manager Console.
Usage
Imagine we have list of Persons in a CSV file
persons.csv
with their first name, last name and birthdate.The corresponding domain model in our system might look like this.
When using TinyCsvParser you have to define the mapping between the columns in the CSV data and the property in you domain model.
And then we can use the mapping to parse the CSV data with a
CsvParser
.User Guide
A full User Guide is available at: