FileHelpers FieldConverter doesn't get called if value is whitespace

1.6k views Asked by At

I am trying to parse a file using FileHelpers. I need to map fields to a KeyValuePair and for a few of these fields, there is a mapping if the string in the file is whitespace. However, my custom FieldConverter's FieldToString method does not seem to be called when the string from the file is whitespace. I want it to be called though!

Here is my field definition:

[FieldFixedLength(1)]
[FieldTrim(TrimMode.Right)]
[FieldConverter(typeof(AreYouOneOfTheFollowingConverter))]
public KeyValuePair<int, string>? AreYouOneOfTheFollowing;

Here is my converter ([case " ":] is never hit):

public class AreYouOneOfTheFollowingConverter : ConverterBase
{
    public override object StringToField(string from)
    {
        switch (from)
        {
            case "1":
                {
                    return new KeyValuePair<int, string>(1469, "Yes");
                }
            case " ":
                {
                    return new KeyValuePair<int, string>(1470, "No");
                }
            default:
                {
                    if (String.IsNullOrWhiteSpace(from))
                    {
                        return from;
                    }
                    else
                    {
                        throw new NotImplementedException();
                    }
                }
        }
    }
}

Ideas?

1

There are 1 answers

0
shamp00 On

ConverterBase has a virtual method you can override to control the automatic handling of white space.

public class AreYouOneOfTheFollowingConverter : ConverterBase
{
    protected override bool CustomNullHandling
    {
        /// you need to tell the converter not 
        /// to handle empty values automatically
        get { return true; } 
    }

    public override object StringToField(string from)
    {
         /// etc...
    }
}