Writing a Custom Configuration Section

Writing your own configuration section involves following steps: -

  1. Define xml structure that will fulfill your configuration needs
  2. Write a class that will represent your custom section by inheriting it from System.Configuration.ConfigurationSection
  3. Add your section, assembly and type representing it, in configSections in your config file.
  4. Add your section anywhere in your config file, within <configuration> root.
  5. Retrieve your custom section using ConfigurationManager.GetSection(“<SectionName”>”)

Please note that to use ConfigurationSection class you need to add reference to System.Configuration.dll in your project.

Consider Following xml structure:

<customSection assembly=”FirstAssembly” type=”FirstAssembly.FirstClass” shouldrun=”true”/>

Following code snippet defines handler for this configuration structure.

class CustomSectionHandler:ConfigurationSection
        public CustomSectionHandler()

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

        public string Type
            get { return (string)this["type"]; }
            set { this["type"] = value; }

        public bool ShouldRun
            get {return (bool)this["shouldrun"];}

Here you have define a CustomSectionHandler class that is inheriting from Configuration.ConfigurationSection class then you have define three properties (representing three attributes of the custom section) and you have decorated all these properties with ConfigurationProperty Attribute.

Next add your section in your .config file in the configSections

    <section name=”customSection” type=”ConfigurationDemo.CustomSectionHandler, ConfigurationDemo”/>

where name is; just name of your section using which you can refer to it in your code and your configuration files while type is “<fully qualified name of handler type>,<Assembly that contains it>”.

SO that was it, your custom section handler is ready, now you can put it to your service like this,

CustomSectionHandler mySectionHandler = (CustomSectionHandler) ConfigurationManager.GetSection(“customSection”); 

string assembly = mySectionHandler.Assembly; 
string type = mySectionHandler.Type; 
bool shouldRun = mySectionHandler.ShouldRun;


Happy Programming!

About these ads