Kirk Evans Blog

.NET From a Markup Perspective

.NET custom configuration sections: NameValueSectionHandler and DictionarySectionHandler

I recently saw a question posted on working with configuration files in .NET. 

> I wanted to do something like
> <appSettings>
> <Servicing>
>      <add key=”Report1″ value=”???”/>
>      <add key=”Report2″ value=”???”/>
>      <add key=”Report3″ value=”???”/>
> </Servicing>
> </appSettings>

The answer is documented in MSDN, but you need to combine several help topics to get the complete picture.  So this one’s for those who program via a web search engine.

When you use the appSettings element in your configuration file, it requires the following structure:

  <add key=”keyname” value=”value” />
  <remove key=”keyname“/>
  <clear />

Each keyname value is unique (hence, the attribute name “key”).  The only valid child element names of “appSettings” are add, remove, and clear.  So, attempting to add your own element as a child of appSettings will not work.

If you need something more flexible than this, there are several ways to create custom configuration sections.  There are several configuration section handlers provided by .NET.  If you would like the return value to be a name/value pair contained in a System.Collections.Specialized.NameValueCollection, use a NameValueSectionHandler.  If instead you want to have the return stored in a System.Collections.Hashtable, use a DictionarySectionHandler.

Both DictionarySectionHandler and NameValueSectionHandler use the same structure as the appSettings element (noted above), with one exception:  you would use your own element name in place of “appSettings”.  Further, you can define custom groups of configuration sections.

<?xml version=”1.0″ encoding=”utf-8″ ?>
  <sectionGroup name=”MyCustom”>
   <section name=”Servicing” type=”System.Configuration.NameValueSectionHandler” />
   <section name=”Maintaining” type=”System.Configuration.DictionarySectionHandler” />
   <add key=”Report1″ value=”value1″ />
   <add key=”Report2″ value=”value2″ />
   <add key=”Report3″ value=”value3″ />
   <add key=”Page1″ value=”value4″ />
   <add key=”Page2″ value=”value5″ />
   <add key=”Page3″ value=”value6″ />

The code to access the sections is simple once you have everything in place.

Imports System.Configuration
Imports System.Collections
Imports System.Collections.Specialized

Module Module1

    Sub Main()
        Dim col As NameValueCollection
        col = CType(ConfigurationSettings.GetConfig(“MyCustom/Servicing”), NameValueCollection)

        Dim hash As Hashtable
        hash = CType(ConfigurationSettings.GetConfig(“MyCustom/Maintaining”), Hashtable)
    End Sub

End Module

The output to the Console window would be: