简体   繁体   中英

Parse appsetting value from string to array of strings

In app.config I have custom section with custom element.

<BOBConfigurationGroup>
    <BOBConfigurationSection>
        <emails test="test1@test.com, test2@test.com"></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();
    }
}

Consider an approach like:

    [ConfigurationProperty("test")]
    public string Test
    {
        get { return (string) base["test"]; }
        set { base["test"] = value; }
    }

    public string[] TestSplit
    {
        get { return Test.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); }
    }

Where TestSplit is the property you use within your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM