Search code examples
c#filehelpers

persist values from read-only properties in FileHelpers


Is there a way that FileHelpers stores any read-only property?

I supposed there would be a solution using aFileHelpers field attribute, but such an attribute does not seem exist. (Just the opposite one called FieldHidden attribute exists).

The situation (code) is as follows

[DelimitedRecord(";")]
public class MigrationFlags
{
    public const string HostUrlTemplate = "{HostUrl}";
    public MigrationFlags()
    {
    }

    [FieldHidden]
    public string Url { get; set; }

    [FieldCaption("RelativeUrl " + HostUrlTemplate)]
    public string RelativeUrl => UriExt.GetRelativeUrl(this.Url);

Here I need to add the RelativeUrl.

It appeared to me to use a converter on the Url property also, but is it possible to use a different solution where I can benefit from that already existing property named RelativeUrl?


Solution

  • I do not recommend using the FileHelpers class for anything other than specifying the CSV file's format. The class represents one record in that file. Think of the syntax of your MigrationFlags class as a clever way of describing a record that FileHelpers can read and write automatically.

    If you need to do add any further logic, it should be in a separate class that you map to/from as necessary. This separates the concerns - MigrationFlags defines the CSV record.

    [DelimitedRecord(";")]
    public class MigrationFlags
    {   
        // Extremely simple class.
        // Only the fields in the CSV
        // No logic. Nothing clever.
        public string RelativeUrl { get; set;};
    }
    
    public class MigrationClass
    {   
        // A normal C# class with:
        //   constructors
        //   properties
        //   methods
        //   readonly, if you like
        //   inheritance, overrides, if you like
        // etc.
    
        public string Url { get; set; }
        public string RelativeUrl => UriExt.GetRelativeUrl(this.Url);
    }
    

    Then to export, something like:

    public void Export(IEnumerable<MigrationClass> items, string filename)
    { 
        var migrationFlags = items.Select(
            x => new MigrationFlags() 
               { 
                 RelativeUrl = x.RelativeUrl,
                 // etc.
               });
    
        var engine = new FileHelperEngine<MigrationFlags>();
        engine.WriteFile(filename, migrationFlags);
    }
    

    See this answer for more information.