CSV parser for C#
Need to parse CSV (Comma Separated Values) files in C#? There are many solutions starting from the OLE DB adapter, but here's an easy-to-use CSV Parser written in pure C#: CSVReader.cs. Now, here's a quick tutorial.
First, let's recite the rules of CSV: Each line in a text file represents a record. The fields on each line are separated by commas. If a field starts by a double quote ("), the field ends when the next quote is encountered. If you need to embed a quote inside a quoted field, use a double quote (""). Take for example the next trivial CSV file:
my fields,go,here
John said: "Don't move","""I won't"", he replied"
The first line parses into three separate fields ("my fields", "go", "here"). The second one is trickier, but it produces two values. You need to note that the quotes in the first field (John said: "Don't move") do not mean field boundaries. The behavior would be different if a double quote started the field, as it does for the second field ("I won't", he replied). This is why the quotes don't need doubling for the first field.
Now, the CSVReader class can be used to read the file like this:
using (CSVReader csv = new CSVReader(@"c:\myfile.csv")) {
string[] fields;
while ((fields = csv.GetCSVLine()) != null) {
Console.WriteLine("New CSV line begins");
foreach (string field in fields)
Console.WriteLine("CSV field: " + field);
}
}
And as you can guess, the code produces output like this:
New CSV line begins CSV field: my fields CSV field: go CSV field: here New CSV line begins CSV field: John said: "Don't move" CSV field: "I won't", he replied
