Get multiple instances of the same key within custom section

1.1k views Asked by At

In my app.config file I have a custom section under configuration with multiple entries that share the same key.

<setion1>
    <add key="key1" value="value1"/>
    <add key="key2" value="value2"/>
    <add key="key1" value="value3"/>
</section1>

I'm using the following code to get a NameValueCollection object from reading the entries.

var list = (NameValueCollection)ConfigurationManager.GetSection("section1");

I expected this code to return each entry under the section however it seems to only bring back unique values with respect to the key. How can I collect all the children of <section1> irrespective of the keys?

2

There are 2 answers

0
Christopher On BEST ANSWER

keys have to be by definition unqiue.

"I have to store mail recipients in the app.config. Each section has it's own list of MailTo and CC entries and the section name dictates which group to send the mail out to."

Then you do not have a bunch of key/mail pairs.

You have a bunch of key/mail[] pairs.

For each key, you have a collection of values. So you use a collection of values. To wich the answer would be this: https://stackoverflow.com/a/1779453/3346583

Of course in that case, scaleability might be a problem. But if you need scaleabiltiy, you propably should solve that as a 1:N relationship in a database/XML File/other data structure anyway. Rather then app.onfig entries.

0
marsze On

You should not use NameValueCollection. It has bad performance and concatenates values for duplicate keys.

You could use KeyValuePair´s and create your own handler for that:

using System;
using System.Configuration;
using System.Collections.Generic;
using System.Xml;
using KeyValue = System.Collections.Generic.KeyValuePair<string, string>;

namespace YourNamespace
{
    public sealed class KeyValueHandler : IConfigurationSectionHandler
    {
        public object Create(object parent, object configContext, XmlNode section)
        {
            var result = new List<KeyValue>();
            foreach (XmlNode child in section.ChildNodes)
            {
                var key = child.Attributes["key"].Value;
                var value = child.Attributes["value"].Value;
                result.Add(new KeyValue(key, value));
            }
            return result;
        }
    }
}

Configuration:

<configSections>
  <section name="section1" type="YourNamespace.KeyValueHandler, YourAssembly" />
</configSections>
<setion1>
    <add key="key1" value="value1"/>
    <add key="key2" value="value2"/>
    <add key="key1" value="value3"/>
</section1>

Usage:

var list = (IList<KeyValue>)ConfigurationManager.GetSection("section1");