Skip to content

Fluent Class Mapping

Christian Droulers edited this page Apr 29, 2015 · 8 revisions

You can map custom class properties to CSV fields using a separate class mapping file. This is useful if you don't have control over the classes you need to read and write with.

CSV File

String Field,Guid Field,Int Field
row 1,11111111-1111-1111-1111-111111111111,1
row 2,22222222-2222-2222-2222-222222222222,2
row 3,33333333-3333-3333-3333-333333333333,3

Custom Class

public class CustomClass
{
    public string StringProperty { get; set; }
    public Guid GuidProperty { get; set; }
    public int IntProperty { get; set; }
}

Mapping By Field Names

You can map class properties to CSV fields using the header names.

public sealed class CustomClassMap : CsvClassMap<CustomClass>
{
    public CustomClassMap()
    {
        Map( m => m.StringProperty ).Name( "String Field" );
        Map( m => m.GuidProperty ).Name( "Guid Field" );
        Map( m => m.IntProperty ).Name( "Int Field" );
    }
}

Mapping By Indexes

You can map class properties to CSV fields using the index of the field.

public sealed class CustomClassMap : CsvClassMap<CustomClass>
{
    public CustomClassMap()
    {
        Map( m => m.StringProperty ).Index( 0 );
        Map( m => m.IntProperty ).Index( 2 );
        Map( m => m.GuidProperty ).Index( 1 );
    }
}

Ignoring Properties

If you want a property to be skipped when reading or writing, ignore the field.

public sealed class CustomClassMap : CsvClassMap<CustomClass>
{
    public CustomClassMap()
    {
        Map( m => m.StringProperty ).Index( 0 );
        Map( m => m.GuidProperty ).Ignore();
        Map( m => m.IntProperty ).Ignore();
    }
}

Using Custom Type Converters

If you have a type that can't be automatically converted, you can use a custom type converter.

public sealed class CustomClassMap : CsvClassMap<CustomClass>
{
    public CustomClassMap()
    {
        Map( m => m.StringProperty ).Index( 0 );
        Map( m => m.GuidProperty ).Index( 1 );
        Map( m => m.IntProperty ).Index( 2 ).TypeConverter<MyCustomTypeConverter>();
    }
}

Mapping Example

The following example demonstrates how to use a class mapping by adding it to the Configuration.ClassMapping property.

using (CsvHelper csv = new CsvReader(File.OpenText("data.csv")))
{
    csv.Configuration.RegisterClassMap<CustomClassMap>();

    IEnumerable<CustomClass> data = csv.GetRecords<CustomClass>();
}
Something went wrong with that request. Please try again.