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.