Reputation: 1533
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.
Upvotes: 4
Views: 4216
Reputation: 4758
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;
}
Upvotes: 6
Reputation: 1533
As mentioned by @TYY, I wrote my own "multiuse" converter, just like this:
public StringNumberCharConverter(
string Size,
string PaddingChar,
string PaddingType,
string RemoveSpecialChars)
{
//implementation here
}
Since FileHelpers converters accept string args only, I had to parse everything on proper objects inside the Converter constructor.
For the parameters, I've converted "Size" to an "integer", PaddingChar onto a "char", PaddingType onto a custom padding type enum (i.e: Padding.LEFT or Padding.RIGHT, so if a "left" is comming from parameters, I should use String.PadLeft() and so on), and the "RemoveSpecialChars" parameter were converted onto a boolean (flag to check if the converter should remove special characters or not.)
Since I need Object-to-File conversion, all the conversion logic is inside "FieldToString" method implementation of ConverterBase abstract method.
Upvotes: 0
Reputation: 2716
FileHelpers has an attribute [FieldFixedLength(xxx)], I believe this should get you what you are looking for (http://filehelpers.sourceforge.net/attributes.html).
Upvotes: 1