Search code examples
c#csvhelper

CsvHelper Ignore case for header names


I have some class

public class Import
{
    public DateTime Date { get; set; }
    public string Category { get; set; }
}

In csv file header names can be in lowercase. How I can ignore case while reading file?

    var reader = new StreamReader(@"///");
    var csv = new CsvReader(reader);
           
    var records = csv.GetRecords<Import>().ToList();

Solution

  • If you are using the http://joshclose.github.io/CsvHelper/ you can provide some configuration when constructing the CsvReader or configuring it after construction.

        using (var stringReader = new StringReader(yourString))
        using (var csvReader = new CsvReader(stringReader))
        {
            // Ignore header case.
            csvReader.Configuration.PrepareHeaderForMatch =  (string header, int index) => header.ToLower();
            return csvReader.GetRecords<Import>().ToList();
        }
    

    There is more documentation in the PrepareHeaderForMatch section at https://joshclose.github.io/CsvHelper/api/CsvHelper.Configuration/Configuration/

    For more granularity there are also class mapping instructions for which can be found under here: https://joshclose.github.io/CsvHelper/examples/configuration

    Hope that helps.