JoshClose / CsvHelper

Library to help reading and writing CSV files
http://joshclose.github.io/CsvHelper/
Other
4.65k stars 1.05k forks source link

Removing whitespace from header and change the header to lowercase #2178

Open Steve1200 opened 11 months ago

Steve1200 commented 11 months ago

I'm trying to remove any whitespace in the header and also change the header to lowercase so that it can match with the class member.

I've tried the code below but it doesn't worked for me.

var csvConfig = new CsvConfiguration(CultureInfo.InvariantCulture) { PrepareHeaderForMatch = header => Regex.Replace(header.Header, " ", string.Empty).ToLower() };

I've also tried to add attribute to the class member but it doesn't seem to work for me too.

[Name("Read Role")] public string readrole { get; set; }

Are there anything I missed in order to change the format of the header before reading the records from the file?

Rob-Hague commented 11 months ago

Can you provide a small example which fails? This works for me:


void Main()
{
    var csvConfig = new CsvConfiguration(CultureInfo.InvariantCulture)
    {
        PrepareHeaderForMatch = header => Regex.Replace(header.Header, " ", string.Empty).ToLower()
    };

    string csv = """
    Read Role,Column 2
    value1,value2
    """;

    using var stringReader = new StringReader(csv);
    using var csvReader = new CsvReader(stringReader, csvConfig);

    var records = csvReader.GetRecords<MyClass>().ToList();
}

class MyClass
{
    public string readrole { get; set; }
    public string column2 { get; set; }
}
Steve1200 commented 11 months ago
Capture2
Rob-Hague commented 11 months ago

It looks fine but in this case a picture is not worth much. Can you give a runnable example like mine? What exactly is not working? Are you getting an error?