Search code examples
c#filehelpers

How to comment or ignore a line in the txt file using FileHelpers


IgnoreFirst(int) or IgnoreLast(int) only ignore a fixed number of lines as header or footer. But I like to ignore or comment a specific line(s) in the txt/csv file. For example like below (ignore some paragraphs or a specific line in 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

I have read about BeforeReadRecord and SkipThisRecord that could potentially resolve this problem, but the documentation is as simple as the image, and has no explanation nor supply an example.

enter image description here


Solution

  • You'll have to use something like this to register the event handler:

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

    and then in the handler, you can check for specific conditions to skip a record:

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

    May be you can just check if it starts with an integer and skip if it doesn't.

    EDIT: You can also use the INotifyRead Interface inside the record like this:

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