Click here to Skip to main content
15,867,453 members
Articles / Web Development / ASP.NET
Article

Understanding Section Handlers - App.config File

Rate me:
Please Sign up or sign in to vote.
4.51/5 (56 votes)
15 Jul 20054 min read 615.8K   7K   165   46
This article explains configuration section handlers defined in the System.Configuration namespace and explains how to create custom sections handlers by implemeting the IConfigurationSectionHandler interface.

Introduction

This article explains configuration section handlers defined in the System.Configuration namespace and explains how to create custom section handlers by implementing the interface IConfigurationSectionHandler.

What we can do with App.config?

A configuration file can contain information that the application reads at run time. We can use configuration sections to specify this information in configuration files. The .NET Framework provides several predefined configuration sections and developers can also create custom configuration sections.

Configuration sections have two parts: a configuration section declaration and the configuration settings. We can put configuration section declarations and configuration settings in the machine configuration file or in the application configuration file. At run time, section handlers, which are classes that implement the IConfigurationSectionHandler interface, read settings in the machine configuration file first, followed by the application configuration file. Depending on the section handler, either the settings in the application file override the settings in the machine file or the settings from both files are merged.

Note: It’s not a good practice to specify application settings in machine.config file.

There are two types of configuration sections:

  • Predefined configuration section (appSettings).
  • User-Defined configuration section(s).

Predefined configuration Section (appSettings)

The .NET Framework provides a predefined configuration section called appSettings. This section is declared in the Machine.config file as follows:

XML
<section name="appSettings" 
    type="System.Configuration.NameValueFileSectionHandler, 
      System, Version=1.0.5000.0, Culture=neutral, 
      PublicKeyToken=b77a5c561934e089"/>

The sample declaration of the appSettings is:

XML
<appSettings file="appSettings.xml"/>

Application settings are defined in an external file, which should be in the application bin folder.

A sample appSettings.xml is:

XML
<?xml version="1.0" encoding="utf-8"?> 
<appSettings>
    <add key="article" value="Configuration Sections"/>
    <add key="author" value="Palanisamy Veerasingam"/>
</appSettings>

or we can keep the appSettings in the App.config file itself:

XML
<appSettings>
    <add key="author" value="Palanisamy Veerasingam"/>
    <add key="article" value="Configuration Sections"/>   
</appSettings>

ConfigurationSettings.AppSettings is a special property that provides a shortcut to application settings defined in the <appSettings> section of the configuration file. The following example shows how to retrieve the author name defined in the previous configuration section example:

C#
public string GetAuthor()
{
    return (ConfigurationSettings.AppSettings["author"]);
}

User-Defined configuration sections or Custom configuration sections

Declaring custom configuration sections

XML
<configSections>
    <section name="sampleSection"
    type="System.Configuration.SingleTagSectionHandler" />
</configSections>

The <section> element has two properties:

  • The name attribute, which is the name of the element that contains the information the section handler reads.
  • The type attribute, which is the name of the class that reads the information.

We can specify the following values to this type attribute:

  • System.Configuration.NameValueSectionHandler – Provides name-value pair configuration information from a configuration section and returns System.Collections.Specialized.NameValueCollection object.
  • System.Configuration.DictionarySectionHandler - Reads key-value pair configuration information for a configuration section and returns System.Collections.Hashtable object.
  • System.Configuration.SingleTagSectionHandler - Reads key-value pair configuration information for a configuration section and returns the System.Collections.Hashtable object.
  • System.Configuration.IgnoreSectionHandler - Provides a section handler definition for configuration sections read and handled by systems other than System.Configuration. To access this section, we have to parse the whole App.config XML file.
  • User defined section handlers, which implement System.Configuration.IConfigurationSectionHandler.

Also, we can use <sectionGroup> tags for more detailed declaration of our sections as follows:

XML
<sectionGroup name="mainGroup">
<sectionGroup name="subGroup">
    <section ...
</sectionGroup>
</sectionGroup>

I hope that by looking at the sample, you can understand the difference between these handlers. I not yet faced a situation to use IgnoreSectionHandler; in that case using a different file will be a good practice, I think so.

Declaring user-defined section handlers

To declare a user-defined section handler, create a class by implementing the interface System.Configuration.IconfigurationSectionHandler.

A sample class declaration is:

C#
public class MyConfigHandler:IconfigurationSectionHandler{…}

There is only one method defined in the interface IconfigurationSectionHandler with the following signature:

C#
object Create (object parent, object configContext, XmlNode section)
  • parent - The configuration settings in a corresponding parent configuration section.
  • configContext - An HttpConfigurationContext when Create is called from the ASP.NET configuration system. Otherwise, this parameter is reserved and is a null reference.
  • section - The XmlNode that contains the configuration information from the configuration file. Provides direct access to the XML contents of the configuration section.
  • Return value - A configuration object.

Sample SectionHandler class definition follows:

C#
public class MyConfigHandler:IConfigurationSectionHandler
{
    public MyConfigHandler(){}

    public object Create(object parent, 
           object configContext, System.Xml.XmlNode section)
    {
        CCompanyAddr objCompany=new CCompanyAddr();
        objCompany.CompanyName = section.SelectSingleNode("companyName").InnerText;
        objCompany.DoorNo = section.SelectSingleNode("doorNo").InnerText;
        objCompany.Street = section.SelectSingleNode("street").InnerText;
        objCompany.City = section.SelectSingleNode("city").InnerText;
        objCompany.PostalCode = 
          Convert.ToInt64(section.SelectSingleNode("postalCode").InnerText);
        objCompany.Country = section.SelectSingleNode("country").InnerText;
        return objCompany;
    }
}

CCompanyAddr is another class defined with the above used properties with corresponding private members.

I have declared a section in the App.config file as follows:

XML
<configSections>
    ...
    <sectionGroup name="companyInfo">
    <section name="companyAddress" 
            type="ConfigSections.MyConfigHandler,ConfigSections"/>
    </sectionGroup>

</configSections>

ConfigSections is the name of the namespace.

Then the section is declared in App.config file as follows:

XML
<companyInfo> 
    <companyAddress> 
<companyName>Axxonet Solutions India Pvt Ltd</companyName>
<doorNo>1301</doorNo>
<street>13th Cross, Indira Nagar, 2nd Stage</street>
<city>Bangalore</city>
<postalCode>560038</postalCode>
<country>India</country>
    </companyAddress>
</companyInfo>

To read companyAddress settings from App.config, we have to use the ConfigurationSettings.GetConfig as follows:

C#
CCompanyAddr obj = 
  (CCompanyAddr)ConfigurationSettings.GetConfig("companyInfo/companyAddress");
  • ConfigurationSettings.GetConfig - Returns configuration settings for a user-defined configuration section.

Conclusion

I have written a very simple application to understand these section handlers, so I haven’t commented my code. Feel free to reply.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Architect
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionWhat about multiple section declaration inside ConfigSection Pin
Member 128057246-Aug-17 1:28
Member 128057246-Aug-17 1:28 
QuestionQuestion for configHandler Pin
Kaan Sonisik27-Oct-13 18:04
Kaan Sonisik27-Oct-13 18:04 
SuggestionSystem.Configuration.IgnoreSectionHandler - access to the XML Pin
Rich Cain1-Dec-11 1:22
Rich Cain1-Dec-11 1:22 
Hi all,
I just thought it worth commenting that contrary to the article, when using System.Configuration.IgnoreSectionHandler, you don't need to parse the entire app.config.
You can get access to the xml just for that section.

VB
Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
Dim sectXML As System.Configuration.DefaultSection = config.GetSection("MyConfigSection")
Dim xmlString As String = sectXML.SectionInformation.GetRawXml()


Cheers,

Rich.
GeneralMy vote of 5 Pin
Pravin Patil, Mumbai27-Jan-11 1:17
Pravin Patil, Mumbai27-Jan-11 1:17 
GeneralMy vote of 5 Pin
m_n_r23-Jan-11 2:16
m_n_r23-Jan-11 2:16 
GeneralMy vote of 5 Pin
gico19-Jan-11 21:34
gico19-Jan-11 21:34 
GeneralThank you so much Pin
Member 432718811-Jan-11 22:39
Member 432718811-Jan-11 22:39 
QuestionHow to encrypt the section <configsections></configsections> Pin
Member 16523002-Sep-09 10:45
Member 16523002-Sep-09 10:45 
AnswerRe: How to encrypt the section Pin
Aoi Karasu 13-Nov-09 0:13
professional Aoi Karasu 13-Nov-09 0:13 
GeneralProblemas with Windows App Pin
Xavito4-Jun-08 6:57
Xavito4-Jun-08 6:57 
QuestionHow to write and Update the data? Please Help Pin
BhuMan28-Mar-08 0:56
BhuMan28-Mar-08 0:56 
GeneralStoring a collection on your app.config using Section Handlers Pin
Ivan (Zaragoza)17-Oct-07 10:11
Ivan (Zaragoza)17-Oct-07 10:11 
QuestionHow to write data into App.Config Pin
ayurhdfkl13-Sep-07 21:23
ayurhdfkl13-Sep-07 21:23 
GeneralError when running program in VS2005 Pin
garyrg91-Aug-07 5:49
garyrg91-Aug-07 5:49 
QuestionHow to iterate through user defined settings Pin
GrahamCooke12-Jun-07 2:47
GrahamCooke12-Jun-07 2:47 
AnswerRe: How to iterate through user defined settings Pin
Palanisamy Veerasingam12-Jun-07 19:53
Palanisamy Veerasingam12-Jun-07 19:53 
GeneralRe: How to iterate through user defined settings Pin
GrahamCooke12-Jun-07 23:54
GrahamCooke12-Jun-07 23:54 
GeneralRe: How to iterate through user defined settings Pin
GrahamCooke13-Jun-07 0:11
GrahamCooke13-Jun-07 0:11 
Questionencrypting ConnectionStrings section in App.Config file? Pin
Do.It15-Mar-07 3:35
Do.It15-Mar-07 3:35 
QuestionRead any config File using System.Configuartion namespace. Pin
ziaulh11-Feb-07 19:39
ziaulh11-Feb-07 19:39 
QuestionGetting errors with Project level namespace Pin
SBendBuckeye18-Jan-07 13:12
SBendBuckeye18-Jan-07 13:12 
Questionapp.config deploy Pin
arkgroup20-Dec-06 10:02
arkgroup20-Dec-06 10:02 
Generalgreat - thanks :) Pin
MeierM28-Sep-06 20:14
MeierM28-Sep-06 20:14 
QuestionConfig Sections in App.Config Pin
RenuKhot18-Sep-06 19:45
RenuKhot18-Sep-06 19:45 
AnswerRe: Config Sections in App.Config Pin
Palanisamy Veerasingam19-Sep-06 20:27
Palanisamy Veerasingam19-Sep-06 20:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.