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); } } } } }