CsvHelper - a tidy package for working with CSV content

I needed to transform some CSV data recently and my Excel skills are somewhat lacking when it comes to the funky stuff, so I had a hunt around for a solution I could use to run up a quick and dirty console application to do the job for me. I was so diligent I didn't even leave it with its default name of ConsoleApp36483427, it got a proper name!

The package I found is:

PM> Install-Package CsvHelper

Which absolutely rocks!

I had a CSV file which contained many records, all with four fields, those being:

  1. ClientId
  2. Day
  3. TotalTalkTime
  4. TotalCallCount

Getting the data into a strongly-typed IEnumerable was as simple as defining a type to hold the data from the file:

struct Record
    public int ClientId { get; set; }
    public int Day { get; set; }
    public int TotalTalkTime { get; set; }
    public int TotalCallCount { get; set; }

Adding a "using" for CsvHelper and writing a tiny, tiny bit of code:

var filePath = @"sourceFile.csv";
IEnumerable<Record> allRecords = null;

using (var reader = File.OpenText(filePath))
    var csvParser = new CsvParser(reader);
    CsvReader r = new CsvReader(csvParser);
    allRecords = r.GetRecords<Record>().ToArray();


After that I was able to munge the data to my hearts content, fantastic!

About Rob

I've been interested in computing since the day my Dad purchased his first business PC (an Amstrad PC 1640 for anyone interested) which introduced me to MS-DOS batch programming and BASIC.

My skillset has matured somewhat since then, which you'll probably see from the posts here. You can read a bit more about me on the about page of the site, or check out some of the other posts on my areas of interest.

No Comments

Add a Comment