Thursday, September 12, 2013

Simple reading of CSV Files - CsvHelper

In my last project we had to retrieve a huge amount of data from an existing CSV-File. I found a nice, fast, little library on GitHub called CsvHelper.


The easiest approach is to create a target class for this if the columns of the CSV-File does not match to the properties of your default business object.

   1: using System;
   2: using System.Collections.Generic;
   3: using System.IO;
   4: using System.Linq;
   5: using System.Text;
   6:  
   7: using CsvHelper;
   8:  
   9: namespace MK.CsvExample
  10: {
  11:     class Program
  12:     {
  13:         static void Main(string[] args)
  14:         {
  15:             using (TextReader reader = File.OpenText(@"C:\tmp\Users.csv"))
  16:             {
  17:                 var csv = new CsvReader(reader);
  18:                 csv.Configuration.Delimiter = ";";
  19:  
  20:                 var usersFromCsv = csv.GetRecords<User>();
  21:  
  22:                 foreach (var user in usersFromCsv)
  23:                 {
  24:                     Console.WriteLine("{0} {1}, {2}, {3}, {4}",
  25:                         user.Firstname,
  26:                         user.Lastname,
  27:                         user.Street,
  28:                         user.City,
  29:                         user.Country);
  30:                 }
  31:             }
  32:             Console.ReadKey();
  33:         }
  34:     }
  35:  
  36:     /// <summary>
  37:     /// BusinessObject for getting CSV-Informations
  38:     /// Names needs to be the same as in the CSV-File
  39:     /// </summary>
  40:     public class User
  41:     {
  42:         public string Lastname { get; set; }
  43:         public string Firstname { get; set; }
  44:         public string Country { get; set; }
  45:         public string City { get; set; }
  46:         public string Street { get; set; }
  47:     }
  48: }

For usage of CSV-Files created in Excel, you have to change de Delimiter to a semicolon (see line 18).

csv-save

A NuGet package is also available: “PM> Install-Package CsvHelper”

cheers


No comments:

Post a Comment