If you have ever tried to manually read a CSV (Comma-separated values) file using the .NET Framework’s File and StreamReader classes you may have run into issues such as:
- Out of range exceptions
- Encoding issues
- Column order changes ect
There are probably many more depending on the files size and complexity.
First prize is to read the CSV file and map the columns to a POCO object (Plain Old CLR)
In software engineering, a plain old CLR object (POCO) is a simple object created in the Common Language Runtime (CLR) of the .NET Framework which is unencumbered by inheritance or attributes.
Enter the CsvHelper library to help reading and writing CSV files by Josh Close.
CsvHelper is a .NET library for reading and writing CSV files. Extremely fast, flexible and easy to use. Supports reading and writing of custom class objects.
Consider the following CSV file with headings Internal Id,Activity,Project Name,Date,Time Spent In Hours,User
Internal Id,Activity,Project Name,Date,Time Spent In Hours,User
(You can check your system separator under ‘Region’ -> ‘Additional settings…’ -> ‘Numbers’ -> ‘List separator’)
Create your POCO class:
public class CsvContentModel
** For simplicity I made all the properties of type string. You can use CsvHelper’s type converter if you want to convert the integer/dates automatically.*
Create a DefinitionMap to help map the columns with spaces in the names.
If you don’t supply a mapping file, auto mapping will be used. Auto mapping will map the properties in your class in the order they appear in.
sealed class CsvContentModelDefinitionMap : CsvClassMap<CsvContentModel>
Organize your CsvHelper logic into a class.
Your catch blocks should do something more helpful with the Exceptions :)
public class ReadFile
Then call the class
var data = new ReadFile("sample.csv").Get();
The instance of data will now have a reference to a list of type CsvContentModel for your business logic.
CsvHelper has several other powerful features such as Type Converter and Configuration Delimiter.