Sunday, August 28, 2022

[FIXED] How to create the C# mapping class to csvhelper

Issue

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>();
    }
}

Solution

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...
}


Answered By - Mitchell Lane
Answer Checked By - Clifford M. (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.