In app.config I have custom section with custom element.
<BOBConfigurationGroup>
<BOBConfigurationSection>
<emails test="[email protected], [email protected]"></emails>
</BOBConfigurationSection>
</BOBConfigurationGroup>
For emails element I have custom type :
public class EmailAddressConfigurationElement : ConfigurationElement, IEmailConfigurationElement
{
[ConfigurationProperty("test")]
public string[] Test
{
get { return base["test"].ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); }
set { base["test"] = value.JoinStrings(); }
}
}
But when I run my webApp, I get error :
The value of the property 'test' cannot be parsed. The error is: Unable to find a converter that supports conversion to/from string for the property 'test' of type 'String[]'.
Is there any solution to split string in getter?
I can get string value and then split it "manually" when I need array, but in some cases I can forget about it, so better to receive array from start.
JoinStrings - is my custom extension method
public static string JoinStrings(this IEnumerable<string> strings, string separator = ", ")
{
return string.Join(separator, strings.Where(s => !string.IsNullOrEmpty(s)));
}
You can add a TypeConverter
to convert between string
and string[]
:
[TypeConverter(typeof(StringArrayConverter))]
[ConfigurationProperty("test")]
public string[] Test
{
get { return (string[])base["test"]; }
set { base["test"] = value; }
}
public class StringArrayConverter: TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string[]);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return ((string)value).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
return value.JoinStrings();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With