Chris's coding blog

IConfigurationSectionHandler example

January 01, 2010

This is a small snippet for the basics of writing a ConfigurationHandler to read a configuration section from your web.config or app.config. Since I wrote this I’ve moved to the easier ConfigSection way of doing things, there’s an example here.

You start off with the XML definition in the config file:

<configSections>
<section name="mysection" type="MyNamespace.ConfigurationHandler,Mynamespace" />
</configSections>
<mysection>
<security enabled="true" />
<username>bob</username>
</mysection>
view raw gistfile1.xml hosted with ❤ by GitHub

And then define your own parser class, and a Settings class to store the details in:

public class ConfigurationHandler : IConfigurationSectionHandler
{
/// <summary>
/// Creates a <see cref="Settings"/> object from the configuration file.
/// </summary>
/// <seealso cref="Settings"/>
public object Create(object parent, object configContext, System.Xml.XmlNode section)
{
if (section == null)
throw new ArgumentNullException("'section' is null. Check your app.config or web.config exists and is valid.");
try
{
Settings settings = new Settings();
// Security
XmlNode node = section.SelectSingleNode("//security");
if (node != null)
Settings.Security = (node.Attributes["enabled"].Value == "true");
else
throw new Exception("No security node could be found in the web/app.config");
// Username
node = section.SelectSingleNode("//username");
if (node != null)
settings.Username = node.Value;
else
throw new Exception("No username could be found in the web/app.config");
return settings;
}
catch (XPathException ex)
{
// Catch From SelectSingleNode,SelectNodes
throw new Exception("XPathException caught when reading config file", ex);
}
}
}
public class Settings
{
public bool Security { get; set; }
public string Username { get; set; }
}
view raw gistfile1.cs hosted with ❤ by GitHub

And then when you application first initializes, read the settings like so:

var settings = (Settings)ConfigurationManager.GetSection("mysection");

An alternative way of doing this is to make the Settings class responsible for initializing itself inside a static constructor, using the above line. You would then make the Settings class a singleton.

csharp

Chris Small

I'm Chris Small, a software engineer living and working in London. This is my tech blog. Find out more via GithubStackoverflowResume