Does anyone know of an open-source library that allows you to parse and read .csv
files in C#?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
I'm implementing Daniel Pryden's answer in C#, so it is easier to cut and paste and customize. I think this is the easiest method for parsing CSV files. Just add a reference and you are basically done.
Add the
Microsoft.VisualBasic
Reference to your projectThen here is sample code in C# from Joel's answer:
Here, written by yours truly to use generic collections and iterator blocks. It supports double-quote enclosed text fields (including ones that span mulitple lines) using the double-escaped convention (so
""
inside a quoted field reads as single quote character). It does not support:But all of those would be easy enough to add if you need them. I haven't benchmarked it anywhere (I'd love to see some results), but performance should be very good - better than anything that's
.Split()
based anyway.Now on GitHub
Update: felt like adding single-quote enclosed text support. It's a simple change, but I typed it right into the reply window so it's untested. Use the revision link at the bottom if you'd prefer the old (tested) code.
Besides parsing/reading, some libraries do other nice things like convert the parsed data into object for you.
Here is an example of using CsvHelper (a library I maintain) to read a CSV file into objects.
By default, conventions are used for matching the headers/columns with the properties. You can change the behavior by changing the settings.
Sometimes you don't "own" the object you want to populate the data with. In this case you can use fluent class mapping.
I really like the FileHelpers library. It's fast, it's C# 100%, it's available for FREE, it's very flexible and easy to use.
Take a look at A Fast CSV Reader on CodeProject.
You can use Microsoft.VisualBasic.FileIO.TextFieldParser
get below code example from above article