Search code examples
csvhelper

Automatic mapping for public fields instead of properties


My data models consist of public fields instead of properties. I'm keen to use CSVHelper's automatic mapping to write these fields into a .csv file. This works fine for properties - but fields appear to be excluded.

The code below works fine when I provide a ClassMap<> - but that seems inconvenient re: long term maintenance. Is there a way to have it automatically map fields as it would for properties?

void Main()
{
    var records = new List<Foo>
    {
        new Foo { Id = 1, Name = "one" },
    };
    
    using (var writer = new StreamWriter("path\\to\\file.csv"))
    using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
    {
        csv.Context.RegisterClassMap<FooMap>();
        csv.WriteRecords(records);
    }
}

public class Foo
{
    public int Id;
    public string Name;
}

public sealed class FooMap : ClassMap<Foo> {
    public TechMap() {
        AutoMap(CultureInfo.InvariantCulture);

        // I'm very keen to avoid having to map 
        // every field that's to be exported.
        Map(m => m.Id).Name("Id");
        Map(m => m.Name).Name("Name");
    }
}

Solution

  • The solution here is to specify fields as member type. A custom configuration can be passed into the CsvWriter constructor.

    var config = new CsvConfiguration(CultureInfo.InvariantCulture) {
        MemberTypes = MemberTypes.Fields
    };
    

    This works like a charm.