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 …
Discover more from Nishant Rana's Weblog
Subscribe to get the latest posts sent to your email.

dd
LikeLike
Hi Man,
thanks for this article.
Would you know how to programmatically write to a custom section of an app.config file???
LikeLike
Super stuff. Far easier to read than the overview on Microsoft. Thanks.
LikeLike