Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileHelpers: mixing Delimited and Fixed Length Records

Here I have to write out a file which records are Pipe Separated, using FileHelpers and C#. Great part of fields have variable length (so, my records would be [DelimitedRecord("|")] ). But some fields must have fixed length (they must have paddings, specific format and so on).

I've googled a bunch with no goal on how to accomplish that.

Example:

[DelimitedRecord("|")]
public class Customer
{
    public int CustId; //variable length

    public string Name; //variable length

    public decimal Balance; //variable length

    [FieldConverter(ConverterKind.Date, "dd-MM-yyyy")]
    public DateTime AddedDate;

    public int Code; // this one must have 10 characters with "zero-fill", like
             // 153 must look like 0000000153

}

How do I accomplish that? Do I have to use a Converter approach and write my own converter for this?

Thank you in advance.

like image 652
cezarlamann Avatar asked Mar 20 '23 11:03

cezarlamann


1 Answers

For anyone who comes across this question in the future, here is some working code to solve this problem.

This class is a converter which the FileHelper engine will use to convert the integer to a string, padded with 0s up to the size specified in the constructor.

public class PaddedIntConverter:ConverterBase
{
    private int _size;
    public PaddedIntConverter(int size)
    {
        _size = size;
    }

    public override object StringToField(string from)
    {
        return int.Parse(from);
    }

    public override string FieldToString(object from)
    {
        return from.ToString().PadLeft(_size,'0');
    }
}

The converter can then be applied to your class like this:

[FixedLengthRecord(FixedMode.ExactLength)]
public class MyClass{
    [FieldFixedLength(7)]
    [FieldConverter(typeof(PaddedIntConverter), 7)]
    public int RecordCount;
}
like image 154
Slider345 Avatar answered Mar 23 '23 00:03

Slider345