Search code examples
c#filehelpersleading-zero

Padding zeros with FileHelpers


I am using FileHelpers to create NACHA files. Example below

Many of the properties are numeric with leading zeros so they have been defined as strings. Is there an attribute that can pad the leading zeros in the Class property, similar to the way FieldTrim/TrimMode works to remove whitespace?

[FixedLengthRecord()]
public class FileControlRecord
{
    [FieldFixedLength(1)]
    public int RecordTypeCode = 9; //Constant

    [FieldFixedLength(6)]
    public string BatchCount; //Numeric

    [FieldFixedLength(6)]
    public string BlockCount; //Numeric

    [FieldFixedLength(8)]
    public string EntryAddendaCount; //Numeric

    [FieldFixedLength(10)]
    public string EntryHash; //Numeric

    [FieldFixedLength(12)]
    public string TotalDebit; //$$$$$$$$$$cc

    [FieldFixedLength(12)]
    public string TotalCredit; //$$$$$$$$$$cc

    [FieldFixedLength(39)]
    [FieldNotInFile]
    public string RESERVED; //Blank
}

Solution

  • You must use FieldAlign with the padding char:

    [FixedLengthRecord()]
    public class FileControlRecord
    {
        [FieldFixedLength(1)]
        public int RecordTypeCode = 9; //Constant
    
        [FieldFixedLength(6)]
        public string BatchCount; //Numeric
    
        [FieldFixedLength(6)]
        public string BlockCount; //Numeric
    
        [FieldFixedLength(8)]
        public string EntryAddendaCount; //Numeric
    
        [FieldFixedLength(10)]
        public string EntryHash; //Numeric
    
        [FieldFixedLength(12)]
        [FieldAlign(AlignMode.Right, '$')]
        public string TotalDebit; //$$$$$$$$$$cc
    
        [FieldFixedLength(12)]
        [FieldAlign(AlignMode.Right, '$')]
        public string TotalCredit; //$$$$$$$$$$cc
    
        [FieldFixedLength(39)]
        public string RESERVED; //Blank
    }
    

    PS: I recomend you to use the last version of the library:

    https://github.com/MarcosMeli/FileHelpers/releases/latest

    or via NuGet https://www.nuget.org/packages/FileHelpers/