Writing CSV files using CSVHelper package (C#, IEnumerable)

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:

Now add CsvHelper to the program by adding:

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:

Finally create an instance of CSVReader and CSVWriter  and invoke the GetRecords method using the DataRecord class to read the CSV file. 

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.

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.

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:

 

You can download this sample code with CsvHelper and CSV file here:

About Carlos Ferreira

Comments

  1. Can we write the dynamic types into csv format with headers?

  2. Jamie Tieman says:

    Carlos,
    I hope you can help me. I have a website using CSVHelper. I create a CSV very much like your example. My problem is trying to overwrite an existing CSV. It fails on the creation of the TextWriter because IIS has a lock on the file and I know this because if I simply try to delete the file, I get a message that says I can’t because it’s in use by IISExpress.

    • Is there another process which is writing to this file or it is your code that is just creating it and writing it over. Make sure you are wrapping the creation of textwriter with a using block to ensure it gets disposed in case of an error. There are a number of sysinternals utils that can help with finding the process that has the file locked (handle, process explorer), etc.

  3. Where should i write my file path?

  4. It’s nigh on impossible to copy/paste from the code areas on this page.

    • Your right. I use the Crayon Syntax Highlighter for formatting the code. If you move the mouse to the top of the code area a menu bar will appear. There are two options there that might be of interest – copy which will copy the entire code base for you in the clipboard and ‘Open Code in New Window’ which will open a webpage which make is easy to copy the sections of code that you need. Not sure what this is like on a mobile device.

      I used to use SyntaxHighlighter Evolved but found that pages were loading incredibly slow (not sure why) so ended up switching to Crayon Syntax Highligher. If anyone has any suggestions please leave a comment.

    • Oh one other thing – you can download the sources. I keep on forgetting to put it on Github – will need to do that someday.

  5. Pramod kumar says:

    this is very very good blog . it is very help full for reading and writing data in csv File . Thank you so much Carlos Ferreira

  6. Paul Meems says:

    Great tutorial. I have a question. How to also export lists?
    I adjusted your example and added a list of address to your DataRecord class:
    public List Adresses { get; set; }
    After reading the records from the CSV I loop trough each record and add 1 dummy address:
    // Fill list of addresses
    foreach (var record in records)
    {
    record.Adresses = new List {address};
    }

    The I call writer.WriteRecords(records);
    A csv is made but without the addresses.

    Please advice.

    Thanks,
    Paul

  7. Hi Carlos,

    Thank you so much for the step by step tutorial. I tried to follow Josh Close and failed miserably (for which I’m duly ashamed). You on the other hand got me going straight away. If it weren’t for you, I’d still be dodging my boss. You are a life saver.
    Thanks again!!
    Paras.

Leave a Reply

%d bloggers like this: