Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading csv file into a DataTable using C#?

I have a number of Python scripts I wrote a while back, to do some data munging. I need to 'port' some of those scripts to C#.

Python provides a CSV module which facilitates importing CSV data from file into a dictionary. I want to have the same functionality in my library, but since I am new to C#, decided to come in here to ask for the best practices way to import CSV data into a DataTable.

Do I roll my own, or is there a 'CSV module' ala Python?

like image 453
oompahloompah Avatar asked Dec 28 '22 16:12

oompahloompah


2 Answers

I wouldn't try to roll your own. You'll have your work cut out trying to cope with all the weird corner-cases that CSV files can throw at you.

I would recommend Sébastien Lorion's Fast CSV Reader instead:

using (var csv = new CachedCsvReader(new StreamReader(filePath), true))
{
    DataTable Table = new DataTable();
    Table.Load(csv);
}
like image 114
LukeH Avatar answered Jan 08 '23 03:01

LukeH


I didn't find any built-in .NET (this is when I coded my solution in .NET 2.0) features that satisfied my needs, so I used the open source link below. I process about 36000 files a month, it works well and I've yet to have an issue.

CsvReader

like image 25
Eric H Avatar answered Jan 08 '23 03:01

Eric H