你如何实现(和空)BadDataFound

How do you implement (and null) BadDataFound

根据 CsvHelper 入门中的说明,除了 csv.Configuration.BadDataFound 行外,我有以下代码:

using (var csv = new CsvReader(tr, CultureInfo.InvariantCulture))
        {
            List<string> badPeople = new List<string>();
            csv.Configuration.BadDataFound = context => badPeople.Add(context.RawRecord);
            try
            {
                var people = csv.GetRecords<Person>();
                var count = people.Count();
                response = await Http.PostAsJsonAsync("api/people/batch", people);
                Message = $"{response}: {selectedFile.Count} file uploaded";
            }
            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }

我根据以下建议配置了 BadDataFound 行:

在 CsvHelper.Configuration 文档中指出:

Gets or sets the function that is called when bad field data is found. A field has bad data if it contains a quote and the field is not quoted (escaped). You can supply your own function to do other things like logging the issue instead of throwing an exception. Arguments: context

我一直收到 BadDataFound 没有 setter 的错误,根据我在 GitHub 上查看代码时所看到的,这是有道理的。当我 运行 没有 BadDataFound 行时,我收到的错误消息指出可以通过将其置空来忽略 BadDataFound。

更复杂的是,在我能找到的上下文中也没有“RawRecord”。

如何让它工作?

Version 20.0.0 中,Josh“将 CsvConfiguration 更改为只读记录以消除线程问题。”您需要提前创建配置并将其传递到 CsvReader/CsvWriter.

RawRecord 现在在解析器上。

但是,我确实注意到它创建了一个记录,即使有错误的数据,它也将 RawRecord 两次输入 badPeople

void Main()
{
    var badPeople = new List<string>();
    var Message = string.Empty;
    var people = new List<Person>();
    
    var config = new CsvConfiguration(CultureInfo.InvariantCulture)
    {
        BadDataFound = arg => badPeople.Add(arg.Context.Parser.RawRecord)
    };

    using (var tr = new StringReader("Id,FirstName,LastName\n1,Foo,Bar\n2,Foo\"Bar,Baz\n3,Foo\"Baz,Bar"))
    using (var csv = new CsvReader(tr, config))
    {       
        try
        {
            people = csv.GetRecords<Person>().ToList();
            var count = people.Count();
        }
        catch (Exception ex)
        {
            Message = ex.Message;
        }
    }
    people.Dump();
    badPeople.Dump();
}

public class Person 
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}