.NET How To Create and Use Custom Name-Value Config Sections

Making over-use of the .NET’s AppSettings quickly results in a messy configuration file. Especially when several assemblies’ configurations are combined, it’s quite painful trying to figure out which settings are for which assemblies. Some of the assemblies might even use the same setting keys, causing a real configuration nightmare. Therefore to keep things neat and tidy, without a lot of extra effort, create your own name-value configuration groups and sections, using the sectionGroup and NameValueSectionHandler.

1. Declare a new sectionGroup:

<configSections>
<sectionGroup name=”shinobido.util”>

</sectionGroup>
</configSections>

2. Add a section to the sectionGroup:

<configSections>
<sectionGroup name=”shinobido.util”>
<section name=”shinobido.util.auditLogging” type=”System.Configuration.NameValueSectionHanlder”/>
</sectionGroup>
</configSections>

3. Add the new configuration group and section using the named elements. Inside configuration section “add” elements, with key-value attributes store settings, just like AppSettings.

<shinobido.util>
<shinobido.util.auditLogging>
<add key=”applicationName” value=”BlackSun” />
<add key=”cached” value=”true” />
</shinobido.util.auditLogging>
</shinobido.util>

4. Retrieve the settings using ConfigurationSettings.GetConfig(…), and cast the return value to a NameValueCollection.

ConfigurationSettings.GetConfigCodeSnippet

That’s it. Your own custom config-section in 60 seconds.

Advertisements