fieldconverter c# code example
Example: fieldconverter c#
//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
[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:
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(".", "");
}
}
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);