I knocked up a very quick program yesterday to read in a .CSV file and present it to the user in a DataGridView for editing (and eventually saving to a database). While discussing the code with Andrew this morning, he suggested a post in the same vain as Carl Franklin's "Better Know a Framework" from .NET Rocks to go over some of the things the code does, so here it is.

The first trick in my code is to read the entire .CSV file into an array of strings. Nothing fancy required, here - I make use of the built-in File.ReadAllLines method:

var content = File.ReadAllLines(fileName);

Now I have a variable called "content" - an array of strings.

Next I want to loop through those lines, splitting them into the individual comma-separated fields. I start my iterator at 1 so it skips the column header row:

for (int i = 1; i < content.Length; i++)
var line = content[ i ];

In the file I'm reading, I know that there's nothing tricky going on like embedded commas wrapped in double-quotes, so I can just using the string.Split method, like this:

 var fields = line.Split(new char[] { ',' });
if (fields.Length != 6) continue;

My very simple error checking here is just making sure that there are six fields on the line (in case the .CSV file is corrupt in some way). I use the continue keyword to jump back up to the next "for" iteration if something's wrong with that line.

Next I want to parse a few of the fields and populate a custom object with their values. My object in this case is called "KillRecord" (this is a CSV with meat pH readings from carcases). I start by parsing the date using DateTime's TryParseExact method, which lets me specify the exact format I expect the date to be in:

 DateTime date;
if (!DateTime.TryParseExact(
fields[1], "dd/MM/yy",
out date)) continue;

Again I simply continue to the next line if something's wrong - no real error reporting in this utility.

Next I want to parse the pH value, a float:

 float pH;
if (!float.TryParse(fields[4], out pH)) continue;

Pretty straight forward.

Lastly I construct my KillRecord object and add it to a predefined list (a BindingList<KillRecord> that the form's DataGridView is bound to):

 var rec = new KillRecord(date, pH);
So that's my code to read in a .CSV file. Like I said: Nothing fancy. I just wanted to break down some of the things I'm doing for those who might be new to .NET. Adding proper error handling and reporting is left as an exercise to the reader! ;-)