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 可能会解决这个问题,但是文档和图片一样简单,没有解释也没有提供示例。
最佳答案
您必须使用类似这样的方法来注册事件处理程序:
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/