gpt4 book ai didi

asp.net-core - 你如何实现(和空)BadDataFound

转载 作者:行者123 更新时间:2023-12-05 03:44:51 29 4
gpt4 key购买 nike

根据 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; }
}

关于asp.net-core - 你如何实现(和空)BadDataFound,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66213714/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com