4

Suppose I have a Filehelpers class like this:

[DelimitedRecord(",")]
public class SomeRecord
{
    public string Field1;
    public decimal Field2;
}

If I try to import a CSV record like this:

hello,$4.00

I get a FileHelpers.ConvertException: "Error Converting '$4.00' to type: 'Decimal'."

How can I make Filehelpers ignore the $ sign?

dan-gph
  • 16,301
  • 12
  • 61
  • 79

1 Answers1

5

I think you'd need to write your own converter and use that converter for Field2. This isn't that difficult, all you need to do is create a class that extends ConverterBase. For example:

public class CurrencyConverter : ConverterBase
{
    private NumberFormatInfo nfi = new NumberFormatInfo();

    public CurrencyConverter()
    {
        nfi.NegativeSign = "-";
        nfi.NumberDecimalSeparator = ".";
        nfi.NumberGroupSeparator = ",";
        nfi.CurrencySymbol = "$";
    }

    public override object StringToField(string from)
    {
        return decimal.Parse(from, NumberStyles.Currency, nfi);
    }
}

You can then use that converter on your Field2 property:

[DelimitedRecord(",")]
public class SomeRecord
{
    public string Field1;
    [FieldConverter(typeof(CurrencyConverter))]
    public decimal Field2;
}

and the $4.00 will be parsed as 4.00.

Obivously my code above isn't that robust. You may prefer to use TryParse rather than just Parse and return 0 if it fails but you get the idea.

petelids
  • 12,305
  • 3
  • 47
  • 57
  • Great, thanks, Pete. Works as advertised. I don't think it needs a `TryParse`. It would be appropriate to get an exception on bad data. – dan-gph Aug 14 '14 at 00:40