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

标签 c# csv csvhelper

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

相关文章:

c# - MVC 属性路由 - 使用 GET 和 POST 的默认 Controller 索引

node.js - Node.js Stream API 的意外行为

python - 如何将产品信息导出到csv并创建6列?

c# - 使用 CsvHelper 仅将选定的列写入 CSV 文件

c# - 加载到 DataTable 时 NullValues 选项不起作用

c# - 调试期间的 Visual Studio : The function evaluation requires all threads to run

c# - 如何获得 IObservable 的最后已知值?

c# - CsvHelper 并并行查询大型 csv 文件

c# - 从 C++/CLI 托管访问 C# 重载方法

python - 将列表中的值分开以形成坐标对