0
votes

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; }

1
Yes, I believe you answered your own question with your edit. - David Specht
ok, thank you. will give it a try. - Sai Krishna

1 Answers

0
votes

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");
    }
}