Search code examples
c#csvcsvhelper

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?


Solution

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