3

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?

bmay2
  • 382
  • 2
  • 4
  • 17
  • Just a guess, but I'm betting because you have the `FieldTrim` attribute the field is never just a space, but instead would be a empty string. Since the `FieldTrim` attribute is not part of the .Net Library, it's hard to validate. – Nathan Nov 11 '14 at 18:38
  • I removed all of the `FieldTrim` attributes and it does not make a difference. – bmay2 Nov 11 '14 at 18:47
  • Leaving the field as `string` preserves the whitespace though. Is it just expected functionality for the FieldConverter to not check whitespaces? – bmay2 Nov 11 '14 at 18:50
  • 1
    Not sure but I just verified that is what happens. I tried some different attributes trying to force it to recognize the white space, but the engine converts the white space to null automatically. As you've already mentioned, you can use a `String` as the field and the white space will be preserved. – Nathan Nov 11 '14 at 19:41

1 Answers1

3

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...
    }
}
shamp00
  • 11,106
  • 4
  • 38
  • 81