Wednesday, August 20, 2014

Parsing a CSV file in C#

Every so often, I seem to run into a situation in which I need to parse a CSV file in order to read data into a system that I'm working with.  Rather than re-invent the wheel by writing my own parser, I tend to leverage the existing Microsoft.VisualBasic.TextFieldParser to do the work (yes, even though I'm using C#).  Here is some sample C# code that demonstrates how this can be used:


using Microsoft.VisualBasic;
using Microsoft.VisualBasic.FileIO;

...

TextFieldParser parser = new TextFieldParser(@"pathToCSVFile");
parser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
     string[] cols = parser.ReadFields();
     foreach (string col in cols)
     {
          Do something with the info in each field...
     }
}

To make a long story short, this existing Microsoft object will make your life a heck of a lot easier since it tends to handle most scenarios that would require special coding (i.e. properly handling quotes).