在CsvHelper中处理错误的CSV记录 [英] Handling bad CSV records in CsvHelper
问题描述
我希望能够遍历CSV文件中的所有记录,并将所有良好记录添加到一个集合中,并分别处理所有不良"记录.我似乎无法做到这一点,我想我一定很想念东西.
I would like to be able to iterate through all records in a CSV file and add all the good records to one collection and handle all the "bad" ones separately. I don't seem to be able to do this and I think I must be missing something.
如果我尝试捕获BadDataException,则后续读取将失败,这意味着我无法继续读取该文件的其余部分-
If I attempt to catch the BadDataException then subsequent reads will fail meaning I cannot carry on and read the rest of the file -
while (true)
{
try
{
if (!reader.Read())
break;
var record = reader.GetRecord<Record>();
goodList.Add(record);
}
catch (BadDataException ex)
{
// Exception is caught but I won't be able to read further rows in file
// (all further reader.Read() result in same exception thrown)
Console.WriteLine(ex.Message);
}
}
讨论的另一个选项是设置BadDataFound回调操作来处理它-
The other option discussed is setting the BadDataFound callback action to handle it -
reader.Configuration.BadDataFound = x =>
{
Console.WriteLine($"Bad data: <{x.RawRecord}>");
};
尽管调用了回调,但不良记录仍然出现在我的良好列表"中
However although the callback is called the bad record still ends up in my "good list"
在将记录添加到列表中之前,是否可以通过某种方式查询读者以查看记录是否良好?
Is there some way I can query the reader to see if the record is good before adding it to my list?
在此示例中,我的记录定义为-
For this example my Record definition is -
class Record
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
和数据(第一行坏,第二行好)-
And the data (first row bad, second row good) -
"Jo"hn","Doe",43
"Jane","Doe",21
有趣的是,使用MissingFieldException处理丢失的字段似乎完全按照我的意愿运行-引发了异常,但后续行仍然可以读取.
Interestingly handling a missing field with MissingFieldException seems to function exactly as I would like - the exception is thrown but subsequent rows are still read ok.
推荐答案
这是示例我提供了.
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("\"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);
};
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; }
}
这篇关于在CsvHelper中处理错误的CSV记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!