Search code examples
c#filehelpers

How to remove trailing empty lines in FileHelper


Thought it would be easy, but cannot find any methods in FileHelpEngine to remove trailing empty lines in a text or csv file, which causes ReadFile to fail.


Solution

  • If the number of empty lines is known, for example 2, you can use in your record class:

    [IgnoreLast(2)]
    public class ...
    

    Another option is to ignore empty lines but are ignored in any place they appear

    [IgnoreEmptyLines()]
    public class ...
    

    The last thing you can try is to ignore some lines by code using INotifyRead interface like:

    [FixedLengthRecord(FixedMode.AllowVariableLength)]
    [IgnoreEmptyLines]
    public class OrdersFixed
        :INotifyRead
    {
       [FieldFixedLength(7)]
       public int OrderID;
    
       [FieldFixedLength(8)]
       public string CustomerID;
    
       [FieldFixedLength(8)]
       public DateTime OrderDate;
    
       [FieldFixedLength(11)]
       public decimal Freight;
    
    
      public void BeforeRead(BeforeReadEventArgs e)
      {
        if (e.RecordLine.StartsWith(" ") ||
           e.RecordLine.StartsWith("-"))
            e.SkipThisRecord = true;
      }
    
      public void AfterRead(AfterReadEventArgs e)
      {   
        //  we want to drop all records with no freight
        if (Freight == 0)
            e.SkipThisRecord = true;
    
      }
    
    }