Using Custom Configuration Section and Configuration Manager class in .NET – 1

At times instead of using appSettings section we would like to define our own custom section within configuration file.

 

Suppose we  want to create a custom config section in this following manner

 

<SimplConfigSection id=myID name=myName />

 

For implementing the above custom section we need to first define a class inheriting from ConfigurationSection class

 

Add reference to System.Configuration dll.

 

Create a new config section class in the following manner

 

// inherit the class ConfigurationSection

    class SimpleConfigSection : ConfigurationSection

    {

        public SimpleConfigSection()

        {

        }

 

        // using ConfigurationProperty attribute to define the attribute

        [ConfigurationProperty(“id”,IsRequired = true)]

        public String ID

        {

            get

            { return (String)this[“id”]; }

            set

            { this[“id”] = value; }

        }

        // using ConfigurationProperty attribute to define the attribute

        [ConfigurationProperty(“name”, IsRequired = true)]

        public String Name

        {

            get

            { return (String)this[“name”]; }

            set

            { this[“name”] = value; }

        }

    }

 

 

Now to register your custom section do the following

 

<configSections>

<section name=SimplConfigSection            type=Namespace.SimpleConfigSection, Namespace />

</configSections>

 

 

And to use it within the application

 

SimpleConfigSection simpleConfig = (SimpleConfigSection)ConfigurationManager.GetSection(“SimplConfigSection”);

            string id = simpleConfig.ID;

            string name = simpleConfig.Name;

 

 

That’s it …


Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

3 thoughts on “Using Custom Configuration Section and Configuration Manager class in .NET – 1”

Share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s