Testerone
Testerone

Reputation: 63

Getting the wrong header in my CSVWriter (CsvHelper)

I'm attempting to write an header to my CSV writer but I am receiving the wrong value for the header, my code is as below:

The definition class:

public class PersonDefinition
{
    public string First_Name { get; set; }
}

The mapping class:

public sealed class PersonDefinitionMap : CsvClassMap<Person>
{
    public PersonDefinitionMap()
    {

        Map(m => m.First_Name).Name("First Name");
    }
}

In the main program:

using (TextWriter writer = new StreamWriter(csvFilePath))
{
    var csvWriter = new CsvWriter(writer);
    csvWriter.Configuration.Encoding = Encoding.UTF8;             
    csvWriter.WriteHeader<PersonDefinition>();   
}

But the output csv get me the following:

First_Name

Instead my expected

First Name

(Without the space)

Where is the problem here?

Upvotes: 0

Views: 1365

Answers (2)

ProgrammingLlama
ProgrammingLlama

Reputation: 38727

Looking at the documentation, you need to register the class map:

var csv = new CsvReader( textReader );
csv.Configuration.RegisterClassMap<MyClassMap>();

Or in your case:

var csvWriter = new CsvWriter(writer);
csvWriter.Configuration.Encoding = Encoding.UTF8;  
csvWriter.Configuration.RegisterClassMap<PersonDefinitionMap>();             
csvWriter.WriteHeader<PersonDefinition>();

Upvotes: 2

JLRishe
JLRishe

Reputation: 101652

It looks like you haven't registered the mapping.

var csvWriter = new CsvWriter(writer);
csvWriter.Configuration.Encoding = Encoding.UTF8;             
csvWriter.Configuration.RegisterClassMap<PersonDefinitionMap>(); // <-- here
csvWriter.WriteHeader<PersonDefinition>();

Upvotes: 3

Related Questions