Multiple values for a single config key

后端 未结 10 2037
被撕碎了的回忆
被撕碎了的回忆 2020-12-05 01:37

I\'m trying to use ConfigurationManager.AppSettings.GetValues() to retrieve multiple configuration values for a single key, but I\'m always receiving an array o

10条回答
  •  温柔的废话
    2020-12-05 02:37

    I know I'm late but i found this solution and it works perfectly so I just want to share.

    It's all about defining your own ConfigurationElement

    namespace Configuration.Helpers
    {
        public class ValueElement : ConfigurationElement
        {
            [ConfigurationProperty("name", IsKey = true, IsRequired = true)]
            public string Name
            {
                get { return (string) this["name"]; }
            }
        }
    
        public class ValueElementCollection : ConfigurationElementCollection
        {
            protected override ConfigurationElement CreateNewElement()
            {
                return new ValueElement();
            }
    
    
            protected override object GetElementKey(ConfigurationElement element)
            {
                return ((ValueElement)element).Name;
            }
        }
    
        public class MultipleValuesSection : ConfigurationSection
        {
            [ConfigurationProperty("Values")]
            public ValueElementCollection Values
            {
                get { return (ValueElementCollection)this["Values"]; }
            }
        }
    }
    

    And in the app.config just use your new section:

    
        

    and when retrieving data just like this :

    var section = (MultipleValuesSection) ConfigurationManager.GetSection("PreRequest");
    var applications = (from object value in section.Values
                        select ((ValueElement)value).Name)
                        .ToList();
    

    Finally thanks to the author of the original post

提交回复
热议问题