Search code examples
c#filehelpers

C# FileHelpers Excluding Fields From Write


I am using Filehelpers to export a collection of a class to a csv file.

The class is used to store user info and has 5 fields, i want to export different fields in different circumstances. so the collection will either be all new users where i only have values for say fields 1,2,3 or deleted users where only fields 1,4,5 have values. I m declaring the fields as optional, however when i call write file all fields are included in the output.

Does anyone have any idea on teh best way to do this, im a bit stumped.

[FieldOptional()]
          [FieldQuoted('"', QuoteMode.AlwaysQuoted, MultilineMode.NotAllow)]
          public String JobTitle;

          [FieldOptional()]
          [FieldQuoted('"', QuoteMode.AlwaysQuoted, MultilineMode.NotAllow)]
          public String Department;

Solution

  • The FieldOptional attribute is used only when importing to signify that a field may be missing from the import file.

    It is not clear from your question whether you need your field 4 and field 5 to appear empty in the case of a new user, e.g.,

    Field1, Field2, Field3,,,
    

    in which case, you can just set Field4 and Field5 to null.

    Or perhaps you want them omitted completely,

    Field1, Field2, Field3
    

    in which case you can use an AfterWriteEvent. Something like

    var engine = new FileHelperEngine<Person>();
    engine.AfterWriteRecord += engine_AfterWriteRecord;
    
    static void engine_AfterWriteRecord(EngineBase engine, AfterWriteEventArgs<Person> e)
    {
        // trim trailing empty separators
        e.RecordLine = e.RecordLine.TrimEnd(',');
    }
    

    As an alternative to attaching an event, you can have your FileHelpers class implement theINotifyWrite<T> interface

    [DelimitedRecord(",")]
    class User : INotifyWrite<User>
    {
        public string Field1;
        public string Field2;
        public string Field3;
        public string Field4;
        public string Field5;
    
        public void BeforeWrite(BeforeWriteEventArgs<User> e)
        {
        }
    
        public void AfterWrite(AfterWriteEventArgs<User> e)
        {
            e.RecordLine = e.RecordLine.Trim(',');
        }
    }