CsvHelper - 无法将 class object 名称与 csv header 名称匹配,因为有括号

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

在 Visual Studio 2019 中使用 CsvHelper 和 .NET Core 2.2。

我的 csv 文件的 header 名称中包含括号。我无法控制此源 csv 文件的内容。

根据 https://joshclose.github.io/CsvHelper/getting-started 的入门文档,如果您的 class 属性 名称与 csv 文件 header 名称相匹配,我们无需任何配置即可读取该文件。但是在 C# 中 class 属性 名称中不能使用括号。

有没有办法解决这个问题,让我的 class 属性 名称与 header 名称匹配,包括括号?如果没有,我如何指示 Csvhelper 正确处理这个问题?该文档仅涉及调整小写与大写的名称。

来自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.

所以(如果只需要去掉括号就可以匹配,否则按自己的逻辑):

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