Tag Archives: C#

CSV Helper

Biswajeet   March 25, 2014   No Comments on CSV Helper

A .NET library for reading and writing CSV files. Extremely fast, flexible and easy to use. Supports reading and writing of custom class objects.

The first thing to do is to Install CsvHelper.
To install CsvHelper, run the following from the Package Manager Console.

Install-Package CsvHelper 

Now add CsvHelper to the program by adding:

using CsvHelper;

The next step is to create a class which has properties with the same name of the column headings found in the csv file.  Below you will find an example of a class which does this:

public class Customer
{
    public string Name { get; set; }
    public string Address { get; set; }
    public string PhoneNo { get; set; }
    public string Country { get; set; }
} 

Finally create an instance of CSVReader and invoke the GetRecords method using the DataRecord class. Below you will find an example of this:

using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using CsvHelper;
namespace CSVHelperReadSample
{
    internal class Program
    {
       private static void Main(string[] args)
       {
          using (var sr = new StreamReader(@"Customerlist.csv"))
          {
             var reader = new CsvReader(sr);

             //CSVReader will now read the whole file into an enumerable
             IEnumerable<datarecord> records = reader.GetRecords<customer>();

             //First 5 records in CSV file will be printed to the Output Window
             foreach (DataRecord record in records.Take(5))
             {
                 Debug.Print("{0} {1}, {2}, {3}", record.Name, record.Address, record.PhoneNo, record.Country);
             }
         }
      }
   }
}

Static Constructor

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.

Static constructors have the following properties:

  • A static constructor does not take access modifiers or have parameters.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the Load Library method.
  • You can’t overload it.