Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing CSV files in C#, with header

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.

like image 803
David Pfeffer Avatar asked Jan 17 '10 15:01

David Pfeffer


1 Answers

A CSV parser is now a part of .NET Framework.

Add a reference to Microsoft.VisualBasic.dll (works fine in C#, don't mind the name)

using (TextFieldParser parser = new TextFieldParser(@"c:\temp\test.csv")) {     parser.TextFieldType = FieldType.Delimited;     parser.SetDelimiters(",");     while (!parser.EndOfData)     {         //Process row         string[] fields = parser.ReadFields();         foreach (string field in fields)         {             //TODO: Process field         }     } } 

The docs are here - TextFieldParser Class

P.S. If you need a CSV exporter, try CsvExport (discl: I'm one of the contributors)

like image 77
Alex from Jitbit Avatar answered Oct 10 '22 17:10

Alex from Jitbit