Multiple values for a single config key

I'm trying to use ConfigurationManager.AppSettings.GetValues() to retrieve multiple configuration values for a single key, but I'm always receiving an array of only the last value. My appsettings.config looks like

<add key="mykey" value="A"/>
<add key="mykey" value="B"/>
<add key="mykey" value="C"/>

and I'm trying to access with

ConfigurationManager.AppSettings.GetValues("mykey");

but I'm only getting { "C" }.

Any ideas on how to solve this?


Try

<add key="mykey" value="A,B,C"/>

And

string[] mykey = ConfigurationManager.AppSettings["mykey"].Split(',');

The config file treats each line like an assignment, which is why you're only seeing the last line. When it reads the config, it assigns your key the value of "A", then "B", then "C", and since "C" is the last value, it's the one that sticks.

as @Kevin suggests, the best way to do this is probably a value whose contents are a CSV that you can parse apart.


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:

<configSections>
    <section name="PreRequest" type="Configuration.Helpers.MultipleValuesSection,
    Configuration.Helpers" requirePermission="false" />
</configSections>

<PreRequest>
    <Values>
        <add name="C++"/>
        <add name="Some Application"/>
    </Values>
</PreRequest>

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


What you want to do is not possible. You either have to name each key differently, or do something like value="A,B,C" and separate out the different values in code string values = value.split(',').

It will always pick up the value of the key which was last defined (in your example C).