在解析错误时获取整个 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/