Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create the C# mapping class to csvhelper

Tags:

I have a csv file with 40 columns and I want to load it to a datatable using csvhelper. After installing the library, I did this:

using (TextReader reader = File.OpenText(fileName)) {    var csv = new CsvReader(reader);    while (csv.Read()) {        var farmID = csv.GetField(0);        Console.WriteLine(farmID);    } } 

and as you see, I have a console statement and it works perfectly.

However, the csvReader has a constructor that takes a custom class to load the data directly to it.

I tried this:

var record = csv.GetRecord<CSVFileDefinition>(); 

but I got this exception

No properties are mapped for type 'MyProjectName.CSVFileDefinition'. 

because the CSVFileDefinitionis an empty class.

my question is how to fill that class.

This is the library:

http://joshclose.github.io/CsvHelper/

Many thanks

Update 2

The solution that works for me is:

sealed class CSVFileDefinitionMap : CsvClassMap<CSVFileDefinition> {    public CSVFileDefinitionMap()    {       Map(m => m.FRM_ID).Name("FARM ID");       Map(m => m.FRM_OWNER).Name("FARM OWNER ");    } }  class CSVFileDefinition {     public string FRM_ID { get; set; }     public string FRM_OWNER { get; set; } }  using (TextReader reader = File.OpenText(fileName)) {     var csv = new CsvReader(reader);     csv.Configuration.RegisterClassMap<CSVFileDefinitionMap>();     while (csv.Read()) {        var record = csv.GetRecord<CSVFileDefinition>();     } } 
like image 246
Agnieszka Polec Avatar asked Jul 29 '14 13:07

Agnieszka Polec


People also ask

Is C better than C++?

What You Learnt: C is somewhat better than C++ in speed and efficiency. It is easier to code and debug in C than C++. C is default choice for source level programming, like kernel programming, driver development etc.

Why C is a mother language?

1) C as a mother language ? C language is considered as the mother language of all the modern programming languages because most of the compilers, JVMs, Kernels, etc. are written in C language, and most of the programming languages follow C syntax, for example, C++, Java, C#, etc.


1 Answers

It seems that all you need to do is to add a property to the CSVFileDefinition class for each column name you expect to find in the CSV file, and the auto mapping should take care of the rest.

For example, this should pull in the farm ID column providing that the property name matches the column name in the CSV:

public class CSVFileDefinition {     public int FarmId { get; set; }      //... add other columns here... } 
like image 97
Mitchell Lane Avatar answered Oct 05 '22 22:10

Mitchell Lane