2016-08-14 18 views
0

IgnoreFirst(int)或IgnoreLast(int)僅將固定數量的行忽略爲頁眉或頁腳。但我喜歡忽略或註釋txt/csv文件中的特定行。比如像下面(忽略某些段落或TXT/CSV特定行):如何使用FileHelpers評論或忽略txt文件中的某一行

############# 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

回答

5

你將不得不使用這樣的事情來註冊事件處理程序:

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; 
    } 

}