This is a follow-up on my post on how to read a CSV file using Josh Close’s CsvHelper. CsvHelper is a fast and flexible .NET library for reading and writing CSV files.
Below I will now show how to write CSV files using CsvHelper. The example will actually be reading a CSV file and then writing the contents of that CSV into another but doing it three times. Each time we do this we will use another method (WriteRecords for all records at once, WriteRecord for writing one record, and WriteField for writing one field).
Our sample input CSV file will look like the following.
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 CSVWriter and invoke the GetRecords method using the DataRecord class to read the CSV file.
1 2 3 4 |
var reader = new CsvReader(sr); var writer = new CsvWriter(sw); IEnumerable records = reader.GetRecords<DataRecord>().ToList(); |
Once we have the completed we are now ready to write the file out. We first will write the entire file out by using the WriteRecords method. Note this method will also normally write the header out automatically.
1 |
writer.WriteRecords(records); |
We then write the records out again but this time we will do so by iterating thru the records collection and writing the entire record using the WriteRecord method and also by writing the fields of the record using the WriteField method.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
foreach (DataRecord record in records) { //Write entire current record writer.WriteRecord(record); //write record field by field writer.WriteField(record.CommonName); writer.WriteField(record.FormalName); writer.WriteField(record.TelephoneCode); writer.WriteField(record.CountryCode); //ensure you write end of record when you are using WriteField method writer.NextRecord(); } |
One point to note that if you were writing a file using the WriteRecord or WriteField methods, you will not get a header record in the file. If you wish to have a header record us the WriteHeader method (example is commented out in final code).
A 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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using CsvHelper; namespace CSVHelperWriteSample { class Program { static void Main(string[] args) { using (var sr = new StreamReader(@"countrylist.csv")) { using (var sw = new StreamWriter(@"countrylistoutput.csv")) { var reader = new CsvReader(sr); var writer = new CsvWriter(sw); //CSVReader will now read the whole file into an enumerable IEnumerable records = reader.GetRecords<DataRecord>().ToList(); //Write the entire contents of the CSV file into another writer.WriteRecords(records); //Now we will write the data into the same output file but will do it //Using two methods. The first is writing the entire record. The second //method writes individual fields. Note you must call NextRecord method after //using Writefield to terminate the record. //Note that WriteRecords will write a header record for you automatically. If you //are not using the WriteRecords method and you want to a header, you must call the //Writeheader method like the following: // //writer.WriteHeader<DataRecord>(); // //Do not use WriteHeader as WriteRecords will have done that already. foreach (DataRecord record in records) { //Write entire current record writer.WriteRecord(record); //write record field by field writer.WriteField(record.CommonName); writer.WriteField(record.FormalName); writer.WriteField(record.TelephoneCode); writer.WriteField(record.CountryCode); //ensure you write end of record when you are using WriteField method writer.NextRecord(); } } } } } } |
You can download this sample code with CsvHelper and CSV file here: