.netfilehelpers

Output formatting with FileHelpers


I'm using FileHelpers to create fixed length files. In my model I have a double which needs to be outputted in a 0000.00 format. Is there anyway I can specify this with FileHelpers itself or do I need to change my model to a string and do a .ToString(my_format) when creating the model?


Solution

  • Have you tried using FieldConverters from the FileHelpers library?

    Maybe something like this. This is untested, but it might get you on a working path:

    using System;
    using FileHelpers;
    
    internal class MyDoubleConverter : ConverterBase
    {
       public override string FieldToString(object from)
       {
          return ((double) from).ToString("0000.00");
       }
    }
    
    [FixedLengthRecord]
    public class MyRecordType
    {
       [FieldFixedLength(7)]
       [FieldConverter(typeof(MyDoubleConverter))]
       public double MyDouble;
    }
    

    Or this may work, and is even simpler:

    [FixedLengthRecord]
    public class MyRecordType
    {
       [FieldFixedLength(7)]
       [FieldConverter(ConverterKind.Double, "0000.00")]
       public double MyDouble;
    }
    

    But I think that will enforce the 0000.00 for both reading and writing, and I'm wouldn't know whether that works for your scenario.