CSV Parser in one routine/function?

2019-06-05 09:51发布

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)

3条回答
Deceive 欺骗
2楼-- · 2019-06-05 10:38

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>();
查看更多
Explosion°爆炸
3楼-- · 2019-06-05 10:46

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!
    }
}
查看更多
爷、活的狠高调
4楼-- · 2019-06-05 10:48

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

查看更多
登录 后发表回答