'Map different Column Header Names to a single field in the C# entity class using CsvHelper

I have a couple different csv file structures each having a different column Header name on the column 2 and need to map this column values to the field on the c# entity class and was wondering how i can achieve this using CsvHelper.

Ex: one file will have column Header as "ColumnXYZ" and another file will have column Header as "ColumnABC" and using the CsvHelper will have to first check which column Header name exists on the file and then map the column values to "FieldQwe" of an entity. Both Column Header names will not exist on single file. So looking for any thoughts on handling this scenario.

Can i use something like this on the entity field so the AutoMap works just fine?

[Name("ColumnABC", "ColumnXYZ")]
public string Field1{ get; set; }



Solution 1:[1]

You can find some configuration examples at https://joshclose.github.io/CsvHelper/examples/configuration/class-maps

void Main()
{
    using (var reader = new StreamReader("path\\to\\file.csv"))
    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
    {
        csv.Configuration.RegisterClassMap<FooMap>();
        var records = csv.GetRecords<Foo>();
    }
}

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

public sealed class FooMap : ClassMap<Foo>
{
    public FooMap()
    {
        Map(m => m.Id).Name("TheId", "Id");
        Map(m => m.Name).Name("TheName", "Name");
    }
}

Solution 2:[2]

You can use a tag helper

public class Foo
{
    [CsvHelper.Configuration.Attributes.Name("TheId")]
    public int Id { get; set; }
    [CsvHelper.Configuration.Attributes.Name("TheName")]
    public string Name { get set; }
}

See This

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Specht
Solution 2 adinas