Create & Read Custom Section Handlers in C# using IConfigurationSectionHandler


In this article we discuss about how to create custom section handler and how to read custom section from App.config by using IConfigurationSectionHandler interface and System.Configuration namespace.

First we have to create custom section in App.config. It has two parts one is we have to define custom section and another one is we have to declare this custom section. To explain this Open Microsoft Visual Studio 2015 => Create Console Application and name it as CSharpReadAppConfig.

We have to define custom section in <Configuration> section of App.config as shown below.

<?xml version="1.0" encoding="utf-8" ?>

<configuration>   

 

  <AppConfiguration>

    <Person>

      <Id>001</Id>

      <Name>Raj</Name>

    </Person>

    <Person>

      <Id>002</Id>

      <Name>Oscar</Name>

    </Person>

    <Person>

      <Id>003</Id>

      <Name>Bill</Name>

    </Person>

    <Person>

      <Id>004</Id>

      <Name>Smith</Name>

    </Person>

    <Person>

      <Id>005</Id>

      <Name>Obama</Name>

    </Person>

  </AppConfiguration>

</configuration>


Once we define custom section, we have to declare this custom section in the <configSections> section of <Configuration> as shown below.


<?xml version="1.0" encoding="utf-8" ?>

<configuration>

   

  <configSections>

    <section name="AppConfiguration" type="CSharpReadAppConfig.AppConfiguration, CSharpReadAppConfig"/>

  </configSections>

 

</configuration>


The total App.config file after defining and declaring the custom section is as shown below.


App.config

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

   

  <configSections>

    <section name="AppConfiguration" type="CSharpReadAppConfig.AppConfiguration, CSharpReadAppConfig"/>

  </configSections>

  <AppConfiguration>

    <Person>

      <Id>001</Id>

      <Name>Raj</Name>

    </Person>

    <Person>

      <Id>002</Id>

      <Name>John</Name>

    </Person>

    <Person>

      <Id>003</Id>

      <Name>Smith</Name>

    </Person>

    <Person>

      <Id>004</Id>

      <Name>David</Name>

    </Person>

    <Person>

      <Id>005</Id>

      <Name>Mark</Name>

    </Person>

  </AppConfiguration>

</configuration>


As shown above we declare the custom section <AppConfiguration> in <configSections>. Now let’s read this custom section by defining a class and implementing the IConfigurationSectionHandler interface as shown below.


AppConfiguration.cs

using System;

using System.Collections.Generic;

using System.Configuration;

using System.Xml;

 

namespace CSharpReadAppConfig

{

    public class AppConfiguration: IConfigurationSectionHandler

    {

        /// <summary>

        /// Id

        /// </summary>

        public string Id { get; set; }

 

        /// <summary>

        /// Name

        /// </summary>

        public string Name { get; set; }

 

        /// <summary>

        /// Implement IConfigurationSectionHandler Create method

        /// </summary>

        /// <param name="parent"></param>

        /// <param name="configContext"></param>

        /// <param name="section"></param>

        /// <returns></returns>

        public object Create(object parent, object configContext, System.Xml.XmlNode section)

        {

            var persons = new List<AppConfiguration>();

            try

            {

                foreach (XmlNode node in section.ChildNodes)

                {

                    if (node.Name == "Person")

                        ReadPersonNodes(node, persons);

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

            return persons;

        }

 

        /// <summary>

        /// Read Person Nodes

        /// </summary>

        /// <param name="node"></param>

        /// <param name="persons"></param>

        private void ReadPersonNodes(XmlNode node, List<AppConfiguration> persons)

        {

            var person = new AppConfiguration();

            foreach (XmlNode child in node.ChildNodes)

            {

                switch (child.Name)

                {

                    case "Id":

                        person.Id = child.FirstChild.Value;

                        break;

                    case "Name":

                        person.Name = child.FirstChild.Value;

                        break;

                }               

            }

            persons.Add(person);

        }

    }

}

 


We have to use System.Configuration namespace to implement the IConfigurationSectionHandler interface. We have to implement Create() method of IConfigurationSectionHandler interface to read custom configuration section from App.config file.

Now read the custom configuration from App.config file by calling the defined AppConfiguration.cs class as shown below.


Program.cs

using System;

using System.Collections.Generic;

using System.Configuration;

 

namespace CSharpReadAppConfig

{

    class Program

    {

        static void Main(string[] args)

        {

            List<AppConfiguration> personsList = (List<AppConfiguration>)ConfigurationManager.GetSection("AppConfiguration");

 

            Console.WriteLine("There are {0} elements in AppConfiguration", personsList.Count.ToString());

            Console.ReadLine();

        }

    }

}

 

As shown above we are calling the GetSection() method of ConfigurationManager class to read the settings from App.config file.

Note: We have to add System.Configuration.dll to our application to use ConfigurationManager class.

Run the application and it displays number of elements defined in App.config file as shown below.

            


In the same way we can read custom settings sections from Web.config and Machine.config also for Asp.Net Web applications.

 

                                                                                      CSharpReadAppConfig.zip (37.7KB)