1

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)

1
  • 1
    I'm curious as to what you mean by "the standard." To the best of my knowledge there is no standard for CSV. That is exactly why you should avoid trying to code your own parser - you don't want to be the one dealing with everybody else's malformed garbage CSV, let somebody else do it. What "various reasons" justify assuming this burden yourself? Commented Mar 9, 2010 at 0:58

3 Answers 3

5

Reference Microsoft.VisualBasic.FileIO and you can use TextFieldParser

using (var parser =
    new TextFieldParser(@"c:\data.csv")
        {
            TextFieldType = FieldType.Delimited,
            Delimiters = new string[] { "," }
        })
{
    while (!parser.EndOfData)
    {
        string[] fields;
        fields = parser.ReadFields();
        //go go go!
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

What are the advantages of TextFieldParser over using StreamReader, Read each Line & Split method ?
@SivaSankaran because there are additional constraints that aren't covered by simplistic CSV parsing performed by simple splitting of each line. e.g. how to represent the character used as delimiter within a data field, quoting of values etc.
@SivaSankaran RFC4180 provides more info.
2

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

1 Comment

... and then use the CSV support built into the .NET framework and supported by Microsoft. stackoverflow.com/questions/2405787/…
0

Writing your own CSV parser is not easy. There is a lot of edge cases you will run into.

Read: http://www.secretgeek.net/csv_trouble.asp

@spender's answer is probably the closest you'll get using built-in stuff.

Give CsvHelper a try (a library I maintain). It's available on NuGet. It's very lightweight. If you just want a small bit of code, you can just copy CsvParser.cs source and modify it a little. There is basically one function that does all the parsing that's just over 100 lines, including comments. If you want a single routine, that would be a good one to grab.

If you use the CsvHelper library, reading into a collection of custom class objects is easy.

var streamReader = // Create StreamReader to your CSV file.
var csvReader = new CsvReader( streamReader );
var myObjects = csvReader.GetRecords<MyObject>();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.