You can add your own configuration sections in Web.config or App.config file. There might be some good way to do it, if so, please let me know.
Step 1
Add the follwing inside <configSections> tag:
<configSections>
<section name ="customSection" type ="System.Configuration.NameValueSectionHandler"/>
</configSections>
Step 2
Add your custom section before or after <appSettings> but after <configSections>
<customSection>
<add key="key1" value="value1" />
<add key="key2" value="value2" />
</customSection>
Your app.config will be like this
---------------------------------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name ="customSection" type ="System.Configuration.NameValueSectionHandler"/>
</configSections>
<!--<Custom Seciton>-->
<customSection>
<add key="key1" value="value1" />
<add key="key2" value="value2" />
</customSection>
<appSettings>
<add key="tesing" value="abc" />
</appSettings>
<system.web>
</system.web>
</configuration>
--------------------------------------------------------------------------------------------------------------
Step 3
How to access it?
NameValueCollection colCustomSection = (NameValueCollection)ConfigurationManager.GetSection("customSection");
string key, value;
for (int count = 0; count < colCustomSection.Count; count++)
{
// we can get the keys
key = colCustomSection.GetKey(count);
// we can get the values
value = colCustomSection.Get(count);
}
To add multiple sections
Add this inside <configSections>
<configSections>
<sectionGroup name ="customSectionGroup">
<section name ="customSection1" type ="System.Configuration.NameValueSectionHandler"/>
<section name ="customSection2" type ="System.Configuration.NameValueSectionHandler"/>
</sectionGroup>
</configSections>
Add this around your custom section:
<customSectionGroup>
<customSection1>
<add key="key1" value="value1" />
<add key="key2" value="value2" />
</customSection1>
<customSection2>
<add key="key1" value="value1" />
<add key="key2" value="value2" />
</customSection2>
</customSectionGroup>
To access it, just change the path:
NameValueCollection colCustomSection = (NameValueCollection)ConfigurationManager.GetSection("customSectionGroup/customSection1");
customSectionGroup/customSection1 or customSectionGroup/customSection2
|