CsvHelper ignore not working

Ryan Kohn picture Ryan Kohn · Nov 4, 2014 · Viewed 9.2k times · Source

I am using CsvHelper to generate a csv file based on a List, but I would like to avoid writing one of the values. As per the documentation, I used a CsvClassMap to specify the field that I want to ignore. However, the value is still being written to the file.

Here is my class:

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
}

Here is my CsvClassMap:

public sealed class PersonClassMap : CsvClassMap<Person>
{
    public PersonClassMap()
    {
        Map(m => m.Id).Index(0).Name("Id");
        Map(m => m.FirstName).Index(1).Name("First Name");
        Map(m => m.LastName).Index(2).Name("Last Name");

        Map(m => m.MiddleName).Ignore();
    }
}

And this is the code that I am using to generate the output:

var persons = new List<Person>
{
    new Person {Id = 1, FirstName = "Randall", MiddleName = "Michael", LastName = "Perry"},
    new Person {Id = 2, FirstName = "Marigold", MiddleName = "Joanne", LastName = "Mercibar"},
    new Person {Id = 3, FirstName = "Sven", MiddleName = "Ergenfein", LastName = "Olafsson"}
};

using (var csvWriter = new CsvWriter(textWriter))
{
    csvWriter.WriteRecords(persons);
    textWriter.Flush();
}

My output is as follows:

Id,FirstName,MiddleName,LastName
1,Randall,Michael,Perry
2,Marigold,Joanne,Mercibar
3,Sven,Ergenfein,Olafsson

How can I get it to stop writing the MiddleName?

Answer

Ryan Kohn picture Ryan Kohn · Nov 4, 2014

The class map must be registered at runtime in order for CsvHelper to know to use it:

using (var csvWriter = new CsvWriter(textWriter))
{
    csvWriter.Configuration.RegisterClassMap<PersonClassMap>();
    csvWriter.WriteRecords(persons);
    textWriter.Flush();
}

Also note that, in the current version, you don't need to explicitly ignore fields in the class map (although this will change in the future):

Ignore

Currently this is not used. Mapping will only map properties that you specify. In the future there will be an option to auto map within a class map, and any mappings explicitly stated will override the auto mapped ones. When this happens, ignore will be used to ignore a property that was auto mapped.

With that in mind, you could also simplify your class map like so:

public sealed class PersonClassMap : CsvClassMap<Person>
{
    public PersonClassMap()
    {
        Map(m => m.Id).Index(0).Name("Id");
        Map(m => m.FirstName).Index(1).Name("First Name");
        Map(m => m.LastName).Index(2).Name("Last Name");
    }
}