This blog has moved, permanently, to

Thursday, May 14, 2009

Custom Dictionary Sections in .NET Config Files

When you need to add complex configuration structures to .NET config files, you will generally create your own custom configuration section classes, and implement them within your application. However, if you just need a standard key/value pair, you don't need a custom configuration type at all. Instead, you can just define a section using the System.Configuration.DictionarySectionHandler, and there you go - no code required.


Say, for instance, you want a list of status codes that get checked by your application:

In the App.config, define the section and implement the required values:
<section name="StatusCodes" type="System.Configuration.DictionarySectionHandler"  />
  <clear />
  <add key="2" value="Two" />
  <add key="3" value="Three" />
  <add key="4" value="Four" />
  <add key="5" value="Five" />
To read these values in code, all you need to do is the following, and you have a Hashtable containing all the values defined in the config file:
Hashtable statusCodes = ConfigurationManager.GetSection("StatusCodes") as Hashtable;

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.