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
Thanks!
You have a small type before creation of the reader class. Thanks for putting this up.
Thanks! I fixed the problem and the brackets problem as well.
Csvreader doesnt have a GetRecords
Hi Matt –
Sounds like you might have not loaded CSVHelper correctly in your project. Follow the steps for adding it via Nuget in your project. There’s a sample project you can download if you want to experiment (link is at bottom of screen).
Cheers,
Carlos
Ah, I figured it out. I had my .Net framework set to 2.0 when I installed the csvhelper package. Uninstall, change to 4.0, reinstall fixed it.
Also, I noticed there is a difference between this page and the sample project.
IEnumerable should be IEnumerable
IEnumerable DataRecord
Yeah.. i’ve had this problem before. The editor doesn’t like the angle bracket so trys to format it then the code highlighter doesn’t like it. I might need to look around for another alternative. I’ve fixed it for now.
Good News! Will need to update the post to indicate the framework required. Thanks for sharing!
We are trying to parse a csv file in which the the field delimiters are identified by ^ and end of a record identified by ~. I know there is an option for setting the field delimiter in csvhelper but how do we tell it the delimiter for end of a record.
Many Thanks
Hi Hassan –
Thanks for visiting. I looked at the source and it looks like there is not. It doesn’t look like it would be difficult to change if you look at the ReadLine method in CsvParser.cs. I would think that this would be useful for parsing files from legacy systems. i might have a stab at seeing if it can be added later on.
Cheers!
Carlos
That would be great. Thanks.
I just thought of something else, the file we are trying to parse has text fields which could have carriage returns in them so making the end of a record something other than newline is mandatory in situations like this.
Thanks again.
Hassan
In the latest version you can specify this to change the delimiter:
csv.Configuration.Delimiter = “,”;
Thanks for pointing that out!
Thanks fot the help!
Wooooow!! This is very helpful and simple ! Thanks:D
Hello Carlos, Thank you for your sharing. When I run your sample program. I got following error.
“CsvHelper.HeaderValidationException: ‘Header with name ‘CommonName’ was not found. ”
Could you send me your comments on this.
Regards