Click button to edit
Converters: Custom Converter
Explains how to extend the library with a new converter
For fixed length records where you need to read decimal data and you don't have an explicit decimal dot (because this isn't required or a Cobol layout). You read it with a customer converter.
If you want to parse a file with a field that has different parsing rules you can define a CustomConverter.For example, if you have the following source file:
Input.txt
0001250001458800013025
0001260012345600234567
0001270123456702345678
0001280087654300123456
RecordClass.cs
[FixedLengthRecord]
public class PriceRecord
{
[FieldFixedLength(6)]
public int ProductId;
[FieldFixedLength(8)]
[FieldConverter(typeof(MoneyConverter))]
public decimal PriceList;
[FieldFixedLength(8)]
[FieldConverter(typeof(MoneyConverter))]
public decimal PriceEach;
}
The last step is to define the converter, you must inherit from ConverterBase:
MoneyConverter.cs
public class MoneyConverter : ConverterBase
{
public override object StringToField(string from)
{
return Convert.ToDecimal(Decimal.Parse(from) / 100);
}
public override string FieldToString(object fieldValue)
{
return ((decimal)fieldValue).ToString("#.##").Replace(".", "");
}
}
Done !! You actually parse the file with:
RunEngine.cs
var engine = new FileHelperEngine<PriceRecord>();
var res = engine.ReadFile("Input.txt");
foreach (var product in res)
Console.WriteLine("Product {0} price {1}", product.ProductId, product.PriceList);
Console
Product 125 price 145,88
Product 126 price 1234,56
Product 127 price 12345,67
Product 128 price 8765,43