How to Create Custom Configuration Sections Using ConfigurationSection

In the below configuration file, a CustomSettingsGroup is been added. which is having two groups defined, EmailSettings and ServiceSettings. It is same like appSettings.

The only benefit is, you can group the settings information into relevant group rather than putting all into appSettings.
I found is useful when number of configuration settings are more and needs to be categorized for easy maintenance and readability.

In the GetValue mehod just specify the group you want to read from.
  1. public string GetValue(this string key)  
  2. {  
  3.    NameValueCollection group = (NameValueCollection)ConfigurationManager.GetSection("CustomSettingsGroup/ServiceSettings");  
  4.    if (group != null)  
  5.    return group[key].ToString();  
  6.    else  
  7.    return "";  
  8. }  
  9. xml version="1.0" encoding="utf-8" ?>  
  10. <configuration>  
  11.    <configSections>  
  12.       <sectionGroup name="CustomSettingsGroup">  
  13.          <section name="ServiceSettings"type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />  
  14.    <section name="EmailSettings"type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />  
  15.          </sectionGroup>  
  16.    </configSections>  
  17.    <startup>  
  18.       <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />  
  19.    </startup>  
  20.       <connectionStrings>  
  21.    </connectionStrings>  
  22.    <CustomSettingsGroup>  
  23.       <EmailSettings>  
  24.          <add key="MyEmailSettingsKey" value="MyEmailSettingsKeyValue"/>  
  25.       </EmailSettings>  
  26.       <ServiceSettings>  
  27.       <add key="MyServiceSettingsKey" value=" MyServiceSettingsKeyValue" />  
  28.       </ServiceSettings>  
  29.    </CustomSettingsGroup>  
  30.    <appSettings>  
  31.    </appSettings>  
  32. </configuration>  

Ebook Download
View all
Learn
View all