Search code examples
c#.netconfigurationproperty

.net Custom Configuration How to case insensitive parse an enum ConfigurationProperty


One of the ConfigurationProperty I have in my ConfigurationSection is an ENUM. When .net parses this enum string value from the config file, an exception will be thrown if the case does not match exactly.

Is there away to ignore case when parsing this value?


Solution

  • You can use ConfigurationConverterBase to make a custom configuration converter, see http://msdn.microsoft.com/en-us/library/system.configuration.configurationconverterbase.aspx

    this will do the job:

     public class CaseInsensitiveEnumConfigConverter<T> : ConfigurationConverterBase
        {
            public override object ConvertFrom(
            ITypeDescriptorContext ctx, CultureInfo ci, object data)
            {
                return Enum.Parse(typeof(T), (string)data, true);
            }
        }
    

    and then on your property:

    [ConfigurationProperty("unit", DefaultValue = MeasurementUnits.Pixel)]
    [TypeConverter(typeof(CaseInsensitiveEnumConfigConverter<MeasurementUnits>))]
    public MeasurementUnits Unit { get { return (MeasurementUnits)this["unit"]; } }
    
    public enum MeasurementUnits
    {
            Pixel,
            Inches,
            Points,
            MM,
    }