This is 2015, and we shouldn’t be working with CSV files any more, but reality is, they are the most commonly used file exchange method around.
As a C# developer, we can make use of standard String and Array classes and we can read/write CSV files. However, there is a maintenance issue, imagine you have a CSV file with 15+ columns, and now you have been asked to update the code with additional columns. Updating index based columns with additional column is a tedious and error prone task.
There is a better way, use FileHelpers. This is a free and Open Source C# library to handle CSV files related operations.
This can be installed as NuGet package within the project.
I am going to assume that the CSV file has got only 2 columns as following :
And the description column could have double quotes ” and a comma can be included within the double quotes.
Step 1 : Create a simple C# class for the CSV file and add field attributes using FileHelpers as following:
Step 2 : The Second step would be to read the flat CSV file into this object.
And that’s it. In case you have to add more columns or remove any column, all you have to is to update the ‘MyProduct.cs’ class file and update the associated strongly typed code.
Now lets assume the opposite, that you have a some sort of data in the database or CMS or external data source and you want to write that into CSV file.
Using the same ‘MyProduct.cs’ class above, the write method will be as following:
Whoooa! that’s it.