c# - 如何使用 FileHelpers 注释或忽略 txt 文件中的一行

标签 c# filehelpers

IgnoreFirst(int) 或 IgnoreLast(int) 仅忽略固定数量的行作为页眉或页脚。但我喜欢忽略或评论 txt/csv 文件中的特定行。例如如下(忽略 txt/csv 中的某些段落或特定行):

############# This is a comment ##########
/* Some comment paragraph  
some more comments
last line of comment */
1,Foo,FooItem1
2,Foo,FooItem2
3,Goo,GooItem3
#4,Doo,DooItem4 <-- ignore. 
5,Eoo,EooItem5

我读过 BeforeReadRecord 和 SkipThisRecord 可能会解决这个问题,但是文档和图片一样简单,没有解释也没有提供示例。

enter image description here

最佳答案

您必须使用类似这样的方法来注册事件处理程序:

FileHelperEngine engine = new FileHelperEngine(typeof(Orders)); 
// set the event here
engine.BeforeReadRecord += new BeforeReadRecordHandler(BeforeEvent); 

然后在处理程序中,您可以检查特定条件以跳过记录:

private void BeforeEvent(EngineBase engine, BeforeReadRecordEventArgs e)
{
    // skip any bad lines
    if (e.RecordLine.StartsWith("#") || e.RecordLine.StartsWith(" "))
        e.SkipThisRecord = true;
}

也许你可以只检查它是否以整数开头,如果不是则跳过。

编辑:您还可以使用 INotifyRead记录里面的界面是这样的:

public class OrdersFixed
    :INotifyRead
{
    //...

    public void BeforeRead(BeforeReadEventArgs e)
    {
        if (e.RecordLine.StartsWith(" ") ||
           e.RecordLine.StartsWith("-"))
            e.SkipThisRecord = true;
    }

}

关于c# - 如何使用 FileHelpers 注释或忽略 txt 文件中的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38940480/

相关文章:

c# - 由于外键约束无法插入数据库

c# - FileHelpers:混合分隔和固定长度记录

c# - 在 C# 中使用 Filehelpers FileHelperAsyncEngine 没有 header

c# - FileHelpers 在解析大型 csv 文件时抛出 OutOfMemoryException

c# - 将 opentext 更改为 opendialog

c# - IIS 花费大量时间来交付第一个 javascript 和图像文件

c# - 自动转义文本框中输入的特殊字符

c# - 使用 lambda 表达式将对象列表从一种类型转换为另一种类型

c# - 导入MySQL时格式化数据表日期列

c# - 如果值为空格,则不会调用 FileHelpers FieldConverter