Create Custom Configuration Sections in .Net

July 15, 2014 by Anuraj

.Net .Net 3.0 / 3.5 .Net 4.0 ASP.Net ASP.Net MVC Visual Studio

This post is about creating custom configuration sections in .Net. If you search for this topic in internet, you will find lot of code snippets and blog posts(Here is the MSDN link). Unlike that, this post is about a nice tool, .NET Configuration Code Generator which will help you to generate code for you to create custom configuration section. It is a free, open source tool licensed under Apache License 2.0 (Apache).

.NET Configuration Code Generator

You can download it from codeplex - http://nconfiggen.codeplex.com/

And once you generate the custom configuration code, you can access it using ConfigurationManager class.

var person = (PersonSection)ConfigurationManager.GetSection("person");
Console.WriteLine(person.FirstName);
Console.WriteLine(person.LastName);

And you need to modify the app.config file to identify the Person section like this. In this ConsoleApplication10.PersonSection is class and ConsoleApplication10 is the assembly, in which class exists. (This is a template I got from the tool)

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="person" type="ConsoleApplication10.PersonSection, ConsoleApplication10"/>
  </configSections>
  <person first-name="Ryan" last-name="James">
    <intelligence>
      <rank value="10" />
      <rating value="Excellent" />
    </intelligence>
    <height value="6.0" tall="true" />
  </person>
</configuration>

And if you want to keep your configuration file out of the app.config / web.config, you can do something like this.

<configuration>
  <configSections>
    <section name="person" type="ConsoleApplication10.PersonSection, ConsoleApplication10"/>
  </configSections>
  <person configSource="Person.config" />
</configuration>

And your Person.config file will look like this.

<?xml version="1.0" encoding="utf-8" ?>
<person first-name="Ryan" last-name="James">
  <intelligence>
    <rank value="10" />
    <rating value="Excellent" />
  </intelligence>
  <height value="6.0" tall="true" />
</person>

Happy Programming :)

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub