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:
- ClientId
- Day
- TotalTalkTime
- 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!