如何将 CsvHelper 配置为忽略与数据行不同的页脚行?

发布于 2025-01-16 12:43:31 字数 529 浏览 1 评论 0原文

我有一个 CSV 文件,末尾有一个记录计数

id|key|limit
123|1|591
456|2|921
record_count|2

行当我使用类映射通过 CsvHelper 运行此文件时,当它到达 record_count|2 行时,它会抛出异常。我正在通过配置一个 ReadingExceptionOccurred 处理程序来忽略该行来解决这个问题。

csvConfig.ReadingExceptionOccurred = ex =>
{
    if (ex.Exception.Context.Parser.RawRecord.Contains("record_count"))
    {
        return false;
    }

    return true;
};

这可行,但是是否有更“标准”的方法来处理此页脚记录?

I have a CSV file with a record count row at the end

id|key|limit
123|1|591
456|2|921
record_count|2

When I run this with CsvHelper using a class map it throws an exception when it gets to the record_count|2 row. I'm working around it by configuring a ReadingExceptionOccurred handler to ignore that row.

csvConfig.ReadingExceptionOccurred = ex =>
{
    if (ex.Exception.Context.Parser.RawRecord.Contains("record_count"))
    {
        return false;
    }

    return true;
};

This works but is there is a more "standard" method for handling this footer record?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

靖瑶 2025-01-23 12:43:32

您可以在配置中使用ShouldSkipRecord

void Main()
{
    var config = new CsvConfiguration(CultureInfo.InvariantCulture)
    {
        Delimiter = "|",
        ShouldSkipRecord = args => args.Record[0] == "record_count"
    };
    
    using (var reader = new StringReader("id|key|limit\n123|1|591\n456|2|921\nrecord_count|2"))
    using (var csv = new CsvReader(reader, config))
    {      
        var records = csv.GetRecords<Foo>().Dump();
    }
}

public class Foo
{
    public int id { get; set; }
    public int key { get; set; }
    public int limit { get; set; }
}

You could use ShouldSkipRecord in the configuration.

void Main()
{
    var config = new CsvConfiguration(CultureInfo.InvariantCulture)
    {
        Delimiter = "|",
        ShouldSkipRecord = args => args.Record[0] == "record_count"
    };
    
    using (var reader = new StringReader("id|key|limit\n123|1|591\n456|2|921\nrecord_count|2"))
    using (var csv = new CsvReader(reader, config))
    {      
        var records = csv.GetRecords<Foo>().Dump();
    }
}

public class Foo
{
    public int id { get; set; }
    public int key { get; set; }
    public int limit { get; set; }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文