Custom Configuration in your config

This post is to show how to setup a customised configuration section in your app.config or web.conifg of your .NET application

I have written an article on this before, back in 2008, but things have moved on in the libraries and this is the latest and easiest way to create your own customised configuration.

We just need to define our class, inherit from System.Configuration.ConfigurationSection, and add a property per setting we wish to store.

using System;
using System.Configuration;

public class BlogSettings : ConfigurationSection
 private static BlogSettings settings = ConfigurationManager.GetSection("BlogSettings") as BlogSettings;
 public static BlogSettings Settings
 return settings;

 [ConfigurationProperty("frontPagePostCount" , DefaultValue = 20 , IsRequired = false)]
 [IntegerValidator(MinValue = 1 , MaxValue = 100)]
 public int FrontPagePostCount
 get { return (int)this["frontPagePostCount"]; }
 set { this["frontPagePostCount"] = value; }

 [ConfigurationProperty("title" , IsRequired=true)]
 public string Title
 get { return (string)this["title"]; }
 set { this["title"] = value; }

Notice that you use an indexed property to store and retrieve each property value.

Also not a static property named Settings for convenience.

Add your new configuration section to web.config (or app.config).

 <section name="BlogSettings" type="Fully.Qualified.TypeName.BlogSettings, 
 AssemblyName" />
 title="You’ve Been Haacked" />

And to access the new configuration using code it is as simple as:

string title = BlogSettings.Settings.Title;
Response.Write(title); //it works!!!

Here is the source code: Configuration Example

Another article that goes into this in a lot more details can be found on Code Project – Unraveling the Mysteries of .NET 2.0 Configuration