Parsing CSV files in .NET without any third party packages

I am working on a window where there will be five cascading dropdowns, and had been sent a CSV file with the data. Being the lazy type, I wanted to write some code to pull the data into the database, rather than have to do it manually.

The obvious way to do this would be something like this…

foreach (string line in File.ReadAllLines(filePath)) {
  string[] bits = line.Split(',');
  // do things with the bits
}

However, a quick peek at the data showed me that there were commas in there, meaning that the Split() call would split the line incorrectly.

I searched around, and found a few libraries and Nuget packages that offered all sorts of exotic and impressive features, most of which I didn’t need.

Somewhere along the way, I discovered that Microsoft very helpfully included this feature in the .NET framework itself, but unhelpfully hid it in the Microsoft.VisualBasic namespace (why?).

Being a fan of functional programming, I found the API somewhat clunky, but it was pretty easy to use…

TextFieldParser reader = new TextFieldParser(filePath) {
  TextFieldType = FieldType.Delimited,
};
reader.SetDelimiters(",");
while (!reader.EndOfData) {
  string[] line = reader.ReadFields();
  // do things with the bits
}

Pretty easy, and it handled the commas correctly.

You can see the documentation for the TextFieldParser class on MSDN, as well as a how-to article on using it.

Be First to Comment

Please note that all comments are manually approved before being displayed, so don't bother posting spam, I'll just delete it

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.