Skip to content
JoshClose edited this page Jul 9, 2011 · 5 revisions

To map custom class properties to CSV fields, you can use the CsvFieldAttribute.

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

Mapping By Field Names

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

public class CustomClass
{
    [CsvField( Name = "String Field" )]
    public string StringProperty { get; set; }

    [CsvField( Name = "Guid Field" )]
    public Guid GuidProperty { get; set; }

    [CsvField( Name = "Int Field" )]
    public int IntProperty { get; set; }
}

Mapping By Indexes

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

public class CustomClass
{
    [CsvField( Index = 0 )]
    public string StringProperty { get; set; }

    [CsvField( Index = 2 )]
    public int IntProperty { get; set; }

    [CsvField( Index = 1 )]
    public Guid GuidProperty { get; set; }
} 

Ignoring Properties

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

public class CustomClass
{
    [CsvField( Index = 0 )]
    public string StringProperty { get; set; }

    [CsvField( Ignore = true )]
    public int IntProperty { get; set; }

    [CsvField( Index = 1 )]
    public Guid GuidProperty { get; set; }
}

Using Custom Type Converters

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

public class CustomClass
{
    [CsvField( Index = 0 )]
    public string StringProperty { get; set; }

    [CsvField( Index = 1 )]
    public Guid GuidProperty { get; set; }

    [CsvField( Index = 2 )]
    [TypeConverter( typeof( MyCustomTypeConverter ) )]
    public int IntProperty { get; set; }
}

Clone this wiki locally