Custom Configuration Sections

So you want to create some custom config sections, but you don’t want to mess with custom classes that inherit from ConfigurationSection and ConfigurationElement? You just want some logical groups of key-value pairs? Well, friend, I’ve got some good news for you: it’s super easy!

To create a simple collection of key-value pair settings, you can use the NameValueSectionHandler class. Just add a section to your configuration file’s configSections, add your settings, and you’re good to go! (Note that your project will need a reference to System.Configuration.)

Here’s a sample config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="Alabama" type="System.Configuration.NameValueSectionHandler" />
    <section name="Georgia" type="System.Configuration.NameValueSectionHandler" />
  </configSections>
  <Alabama>
    <add key="state" value="ALABAMA!" />
  </Alabama>
  <Georgia>
    <add key="state" value="GEORGIA!" />
  </Georgia>
</configuration>

And here’s the sample code to access the custom sections and settings:

using System;
using System.Collections.Specialized;
using System.Configuration;

namespace MultipleConfigSections
{
    class Program
    {
        static void Main(string[] args)
        {
            var alSection = ConfigurationManager.GetSection("Alabama") as NameValueCollection;
            Console.WriteLine(alSection["state"]);

            var gaSection = ConfigurationManager.GetSection("Georgia") as NameValueCollection;
            Console.WriteLine(gaSection["state"]);

            Console.WriteLine();
        }
    }
}

If you’re looking for something more sophisticated, you’ll probably want to check out this MSDN article for a quick example that uses ConfigurationSection and ConfigurationElement. Need a collection? You’ll probably need ConfigurationElementCollection, too.

Advertisement

Author: Adam Prescott

I'm enthusiastic and passionate about creating intuitive, great-looking software. I strive to find the simplest solutions to complex problems, and I embrace agile principles and test-driven development.

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: