Ignoring properties in FileHelpers
Asked Answered
A

4

8

I am using FileHelpers for exporting models to CSV. It has a [FieldNotInFile()] attribute which excludes fields when exporting, but I need to use properties as I need to some other attributes as well from another 3rd party library which only work with properties.

Is there any way to get FileHelpers to ignore a property?

Allium answered 26/1, 2015 at 16:32 Comment(0)
E
10

I had the same problem the other day and used [FieldHidden] attribute. Something like this:

[DelimitedRecord("\t")]
public class PolicyFileRecord
{
    public string FileDate;
    public int ProgramId;
    public string LocationAddress1;
    public string LocationAddress2;
    public string LocationAddress3;
    public string LocationCity;
    public string LocationState;
    public string LocationZip;

    [FieldHidden] 
    public string LocationCountry;
}
Exegetics answered 2/5, 2016 at 2:5 Comment(0)
S
4

I got this to work by giving the property a backing field and marking the backing field as [FieldHidden]:

[DelimitedRecord(",")]
public class Record
{
    public int Id;
    public string Name;

    public string SomeProperty
    {
        get { return someProperty; }
        set { someProperty = value; }
    }

    [FieldHidden]
    private string someProperty;
}
Simba answered 2/6, 2016 at 2:18 Comment(0)
G
4

Since release3.27, you can use [FieldHidden] on fields AND properties.

Gradeigh answered 6/3, 2018 at 9:39 Comment(0)
O
1

A FileHelpers class is just a way of defining the specification of a flat file using a limited C# syntax as the definition language. As such, the FileHelpers classes are an unusual type of C# class and you should not try to use them in any other way. Think of the FileHelpers class as the 'specification' of your CSV format only. That should be its only role. If you need the records in a more 'normal' object (in your case, you need properties instead of fields), then map the results to something better like this:

FileHelperEngine engine = new FileHelperEngine<FileHelpersOrder>(); 
var records = engine.ReadFile("FileIn.txt");

var niceOrders = records.Select(
    x => new NiceOrder() 
       { Number = x.Number,  
         Customer = x.Customer 
         // etc.
       });

Where FileHelpersOrder is your CSV specification and the NiceOrder class would be a proper OOP class with properties, methods, etc. as necessary.

If you're exporting, then you need to do the opposite, i.e., select a collection of FileHelpersOrder from a collection of NiceOrder.

Orman answered 27/1, 2015 at 13:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.