How to get the values of a ConfigurationSection of type NameValueSectionHandler

120,656

Solution 1

Suffered from exact issue. Problem was because of NameValueSectionHandler in .config file. You should use AppSettingsSection instead:

<configuration>

 <configSections>
    <section  name="DEV" type="System.Configuration.AppSettingsSection" />
    <section  name="TEST" type="System.Configuration.AppSettingsSection" />
 </configSections>

 <TEST>
    <add key="key" value="value1" />
 </TEST>

 <DEV>
    <add key="key" value="value2" />
 </DEV>

</configuration>

then in C# code:

AppSettingsSection section = (AppSettingsSection)ConfigurationManager.GetSection("TEST");

btw NameValueSectionHandler is not supported any more in 2.0.

Solution 2

Here's a good post that shows how to do it.

If you want to read the values from a file other than the app.config, you need to load it into the ConfigurationManager.

Try this method: ConfigurationManager.OpenMappedExeConfiguration()

There's an example of how to use it in the MSDN article.

Solution 3

Try using an AppSettingsSection instead of a NameValueCollection. Something like this:

var section = (AppSettingsSection)config.GetSection(sectionName);
string results = section.Settings[key].Value;

Source: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/d5079420-40cb-4255-9b3b-f9a41a1f7ad2/

Solution 4

The only way I can get this to work is to manually instantiate the section handler type, pass the raw XML to it, and cast the resulting object.

Seems pretty inefficient, but there you go.

I wrote an extension method to encapsulate this:

public static class ConfigurationSectionExtensions
{
    public static T GetAs<T>(this ConfigurationSection section)
    {
        var sectionInformation = section.SectionInformation;

        var sectionHandlerType = Type.GetType(sectionInformation.Type);
        if (sectionHandlerType == null)
        {
            throw new InvalidOperationException(string.Format("Unable to find section handler type '{0}'.", sectionInformation.Type));
        }

        IConfigurationSectionHandler sectionHandler;
        try
        {
            sectionHandler = (IConfigurationSectionHandler)Activator.CreateInstance(sectionHandlerType);
        }
        catch (InvalidCastException ex)
        {
            throw new InvalidOperationException(string.Format("Section handler type '{0}' does not implement IConfigurationSectionHandler.", sectionInformation.Type), ex);
        }

        var rawXml = sectionInformation.GetRawXml();
        if (rawXml == null)
        {
            return default(T);
        }

        var xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(rawXml);

        return (T)sectionHandler.Create(null, null, xmlDocument.DocumentElement);
    }
}

The way you would call it in your example is:

var map = new ExeConfigurationFileMap
{
    ExeConfigFilename = @"c:\\foo.config"
};
var configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
var myParamsSection = configuration.GetSection("MyParams");
var myParamsCollection = myParamsSection.GetAs<NameValueCollection>();

Solution 5

This is an old question, but I use the following class to do the job. It's based on Scott Dorman's blog:

public class NameValueCollectionConfigurationSection : ConfigurationSection
{
    private const string COLLECTION_PROP_NAME = "";

    public IEnumerable<KeyValuePair<string, string>> GetNameValueItems()
    {
        foreach ( string key in this.ConfigurationCollection.AllKeys )
        {
            NameValueConfigurationElement confElement = this.ConfigurationCollection[key];
            yield return new KeyValuePair<string, string>
                (confElement.Name, confElement.Value);
        }
    }

    [ConfigurationProperty(COLLECTION_PROP_NAME, IsDefaultCollection = true)]
    protected NameValueConfigurationCollection ConfCollection
    {
        get
        {
            return (NameValueConfigurationCollection) base[COLLECTION_PROP_NAME];
        }
    }

The usage is straightforward:

Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
NameValueCollectionConfigurationSection config = 
    (NameValueCollectionConfigurationSection) configuration.GetSection("MyParams");

NameValueCollection myParamsCollection = new NameValueCollection();
config.GetNameValueItems().ToList().ForEach(kvp => myParamsCollection.Add(kvp));
Share:
120,656
Admin
Author by

Admin

Updated on July 05, 2022

Comments

  • Admin
    Admin almost 2 years

    I'm working with C#, Framework 3.5 (VS 2008).

    I'm using the ConfigurationManager to load a config (not the default app.config file) into a Configuration object.

    Using the Configuration class, I was able to get a ConfigurationSection, but I could not find a way to get the values of that section.

    In the config, the ConfigurationSection is of type System.Configuration.NameValueSectionHandler.

    For what it worth, when I used the method GetSection of the ConfigurationManager (works only when it was on my default app.config file), I received an object type, that I could cast into collection of pairs of key-value, and I just received the value like a Dictionary. I could not do such cast when I received ConfigurationSection class from the Configuration class however.

    EDIT: Example of the config file:

    <configuration>
      <configSections>
        <section name="MyParams" 
                 type="System.Configuration.NameValueSectionHandler" />
      </configSections>
    
      <MyParams>
        <add key="FirstParam" value="One"/>
        <add key="SecondParam" value="Two"/>
      </MyParams>
    </configuration>
    

    Example of the way i was able to use it when it was on app.config (the "GetSection" method is for the default app.config only):

    NameValueCollection myParamsCollection =
                 (NameValueCollection)ConfigurationManager.GetSection("MyParams");
    
    Console.WriteLine(myParamsCollection["FirstParam"]);
    Console.WriteLine(myParamsCollection["SecondParam"]);
    
  • Admin
    Admin over 13 years
    As i said in my post, This is what i did. I received Configuraion class, and from it i received a ConfigurationSection. My question was how can i get the values from that ConfigurationSection object? i didn't ask how to get the Configuration object.. Thanks anyway!
  • Admin
    Admin over 13 years
    by the way, in the example you gave me they are not using the Configuration class that comes from OpenMappedExeConfiguration, but they are using the default app.config (which can be used using the .GetSection/.GetConfig methods, but as i said in my post- i did that already. but its no good for me since its good for app.config only). and for the msdn, i could not find the answer to my question there..
  • MonkeyWrench
    MonkeyWrench over 13 years
    Ok, the more I look into it, the more I see it isn't easy to do. The basic problem is that you're trying to mix .Net 1.1 configuration style code and 2.0. Read this, it'll point you in the right direction: eggheadcafe.com/software/aspnet/30832856/…
  • nerijus
    nerijus about 11 years
    nope this way you will get "Unable to cast object of type 'System.Configuration.DefaultSection' to type 'System.Configuration.AppSettingsSection'."
  • h9uest
    h9uest about 11 years
    @nerijus : come on man ... Of course one of Steven's assumptions is that you actually change the type of the section accordingly ... No offense, but you really could think before commenting. I tried this solution and it works. +1 for Steven
  • Peter Ivan
    Peter Ivan over 10 years
    @h9uest: It's not so straightforward, as Liran wrote the section is System.Configuration.NameValueSectionHandler. This answer seems more like a kind-of-dirty hack.
  • Jone Polvora
    Jone Polvora over 9 years
    Casting to AppSettings section didn't worked for me. Instead, i've casted to NameValueCollection and worked.
  • Hari
    Hari over 9 years
    @MonkeyWrench The page is no more available.
  • MonkeyWrench
    MonkeyWrench over 9 years
    Looks like bluefeet fixed that. Thanks.
  • MonkeyWrench
    MonkeyWrench about 9 years
    Aw... why the downvote? I can't fix the internet. The link is 5 years old. The MSDN has a good example as well.
  • Liam
    Liam almost 9 years
    This answer appears to be suffering from link rot, this is why link only answers are discouraged.
  • RayLoveless
    RayLoveless over 7 years
    Great blog post. Thanks for sharing.
  • Joseph
    Joseph almost 6 years
    It's so nice to see somebody answering the question asked. I have been digging through reams of answers to questions about handling OpenExeConfiguration GetSection with "answers" that redirect people to ConfigurationManager.GetSection which doesn't so the same thing.
  • Onsokumaru
    Onsokumaru over 5 years
    Downvote: It's a good answer in general about the config topic for the beginner/standard usecase, but it's a useless answer for the specific problem of the initial question. I ran into the same problem as Liran B and the blogpost helps absolutely not. The question is how to deal with the ConfigurationSection-object.
  • Onsokumaru
    Onsokumaru over 5 years
    I had a little bit trouble to get my section working (some mistakes while loading the config file itself), but after that this solution worked perfectly. Now I can split my config file in multiple sections and easily access the values via AppSettingsSection.
  • nivs1978
    nivs1978 almost 4 years
    You should be able to just call the Get method: var myParamsCollection = myParamsSection.Get<NameValueCollection>();
  • aj go
    aj go over 2 years
    not working on my side
  • wavydavy
    wavydavy about 2 years
    When I try the above I'm getting "Unable to find section handler type..." error. In your example what does the XML look like? I'm using the OP XML "<section name="MyParams" type="System.Configuration.NameValueSectionHandler" />"