Search code examples
c#csvhelper

CsvHelper - can't match class object names to csv header names because of parentheses


Using CsvHelper in Visual Studio 2019 with .NET Core 2.2.

The header names of my csv file contain parentheses in the names. I don't have any control over the contents of this source csv file.

Per the getting started documentation at https://joshclose.github.io/CsvHelper/getting-started if your class property names match the csv file header names, we can read the file without any configuration. But parentheses can't be used in class property names in C#.

Is there a way around this so I can make the my class property names match the header names including parentheses? If not, how can I direct Csvhelper to handle this correctly? The documentation only refers to adjusting the names for lowercase vs uppercase.


Solution

  • From the documentation:

    Using the configuration PrepareHeaderForMatch, we're able to change how the header matching is done against the property name. Both the header and the property name are ran through the PrepareHeaderForMatch function. When the reader needs to find the property to set for the header, they will now match. You can use this function to do other things such as remove whitespace or other characters.

    So (if only need to remove the parenthesis to match, otherwise, do your own logic):

    using (var reader = new StreamReader("path\\to\\file.csv"))
    using (var csv = new CsvReader(reader))
    {    
        csv.Configuration.PrepareHeaderForMatch = (string header, int index) => 
            header.Replace("(","").Replace(")","");
        var records = csv.GetRecords<Foo>();
    }