I have come across many times the need to incorporate the reading of CSV files in an application. Below I will show how to use Josh Close’s CsvHelper to import a CSV file which looks like the following (file will be included below).
CommonName,FormalName,TelephoneCode,CountryCode
Argentina,Argentine Republic,54,ARG
Armenia,Republic of Armenia,374,ARM
Australia,Commonwealth of Australia,61,AUS
Austria,Republic of Austria,43,AUT
“Bahamas, The”,Commonwealth of The Bahamas,-241,BHS
Bangladesh,People’s Republic of Bangladesh,880,BGD
Note this CSV file is a simpler file based on the file which is located here.
The first thing to do is to Install CsvHelper. To do this run the following command in the Package Manager Console:
1 |
Install-Package CsvHelper |
Now add CsvHelper to the program by adding:
1 |
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:
1 2 3 4 5 6 7 8 9 |
class DataRecord { //Should have properties which correspond to the Column Names in the file //i.e. CommonName,FormalName,TelephoneCode,CountryCode public String CommonName { get; set; } public String FormalName { get; set; } public String TelephoneCode { get; set; } public String CountryCode { 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:
1 2 |
var reader = new CsvReader(sr); IEnumerable<DataRecord> records = reader.GetRecords<DataRecord>(); |
An completed example can be found below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
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(@"countrylist.csv")) { var reader = new CsvReader(sr); //CSVReader will now read the whole file into an enumerable IEnumerable<DataRecord> records = reader.GetRecords<DataRecord>(); //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.CommonName, record.CountryCode, record.FormalName, record.TelephoneCode); } } } } } |
You can download this sample code with CsvHelper and CSV file here: CVSHelperReadSample