gpt4 book ai didi

c# - 获取错误解析或读取时的整个 CSV 行

转载 作者:行者123 更新时间:2023-12-05 06:30:56 26 4
gpt4 key购买 nike

在解析错误时获取整个 Csv 行

CsvHelper我们使用:

MissingFieldFound:

Gets or sets the function that is called when a missing field is found.The default function will throw a CsvHelper.MissingFieldException.You can supply your own function to do other things like logging the issue instead of throwing an exception. Arguments: headerNames, index, context

BadDataFound:

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

在下面的 MCVE 中,只有 MissingFieldFound 捕获了完整的行,而 BadDataFound 没有。

static void Main()
{
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
using (var reader = new StreamReader(stream))
using (var csv = new CsvReader(reader))
{
writer.WriteLine("FirstName,LastName");
writer.WriteLine("\"Jon\"hn\"\",\"Doe\"");
writer.WriteLine("\"JaneDoe\"");
writer.WriteLine("\"Jane\",\"Doe\"");
writer.Flush();
stream.Position = 0;

var good = new List<Test>();
var bad = new List<string>();
var isRecordBad = false;

csv.Configuration.BadDataFound = context =>
{
isRecordBad = true;
bad.Add(context.RawRecord);
};

csv.Configuration.MissingFieldFound = (headerNames, index, context) =>
{
isRecordBad = true;
bad.Add(context.RawRecord);
};

while (csv.Read())
{
var record = csv.GetRecord<Test>();
if (!isRecordBad)
{
good.Add(record);
}

isRecordBad = false;
}

good.Dump();
bad.Dump();
}
}

public class Test
{
public string FirstName { get; set; }
public string LastName { get; set; }
}

我希望结果是:

"Jon"hn"","Doe"
"JaneDoe"

代替:

"Jon"hn"", "JaneDoe"

对于包含很多列的长 Csv,该行的其余部分通常包含有值(value)的信息。

最佳答案

你可以这样得到一行:

 csv.Parser.Context.RawRecord;

关于c# - 获取错误解析或读取时的整个 CSV 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52006534/

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