views:

96

answers:

2

I know there are several libraries of code out there that can parse CSV files according to the standard, but, for various reasons, I need one simple routine (not an entire library) that parses a CSV into a DataTable or array. Does such an animal exist or is it extinct? (Preferably C# but i can translate vb.net too)

+2  A: 

Write your own method that loops through each line and use the split method using the comma as your delimiter.

If you want to parse a csv using linq, here is a simple example:

http://www.fryan0911.com/2009/05/read-data-from-csv-using-linq.html

Joe Pitz
But see http://www.secretgeek.net/csv_trouble.asp first!
Martin Smith
... and then use the CSV support built into the .NET framework and supported by Microsoft. http://stackoverflow.com/questions/2405787/csv-parser-in-one-routine-function/2405898#2405898
MarkJ
+4  A: 

Reference Microsoft.VisualBasic and you can use TextFieldParser

using (var parser =
    new TextFieldParser(@"c:\data.csv")
        {
            TextFieldType = FieldType.Delimited,
            Delimiters = new[] { "," }
        })
{
    while (!parser.EndOfData)
    {
        string[] fields;
        fields = parser.ReadFields();
        //go go go!
    }
}
spender