Four Ways To Read Configuration Setting In C#

This article will demonstrate how we can get/read the configuration setting from Web.Config or App.Config in C#. There are different ways to set the values inside the configuration file and read their values, which are based on the defined keys. We define those values inside the configuration section, which might be needed to make it more secure. It can be some secret keys or the value, which should be received frequently.

Today, I will show you four different ways to get the values from the configuration section.

For this demonstration, I am going to create a simple console Application and provide the name as “ConfigurationExample”. Just create one console Application, as shown below.

New Project > Visual C# > Console Application


We need to add System.Configuration assembly reference to access configuration settings, using ConfigurationManager. To add the reference, just right click References and click to add references.


Now, we can see that System.Configuration reference has been added successfully to our project.


Thus, let’s move to different ways to add the values inside the config file and the approach we follow to get it.

First approach 

Let’s take one example, where we need to add some Application level settings and access them based on their keys. We can add these settings either inside Web.Config or App.Config but we need to add <appSettings> section inside the configuration section.

Just follow the example given below, where inside the appSettings section; we have defined few keys and their values.

App.config 

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <configuration>  
  3.   <startup>  
  4.     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />  
  5.   </startup>  
  6.   <appSettings>  
  7.     <add key="Title" value="Configuration Example"/>  
  8.     <add key="Language" value="CSharp"/>  
  9.   </appSettings>  
  10. </configuration>  

To access these values, there is one static class named ConfigurationManager, which has one getter property named AppSettings. We can just pass the key inside the AppSettings and get the desired value from AppSettings section, as shown below. 

  1. public static void GetConfigurationValue()  
  2.         {  
  3.             var title = ConfigurationManager.AppSettings["title"];  
  4.             var language = ConfigurationManager.AppSettings["language"];  
  5.   
  6.             Console.WriteLine(string.Format("'{0}' project is created in '{1}' language ", title, language));  
  7.         }   

When we implement the code given above, we get the output, as shown below.


Second approach 

Let’s move to the next example. If we need to add the settings inside the section for the separation, in this situation, we can create a custom section inside the configuration section in App.Config/Web.Config, as shown below. This section can make your data more readable and understandable based on your section name.

In the example given below, we have just created one custom section named ApplicationSettings and added all the key/value pairs separately. 

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <configuration>  
  3.    <configSections>  
  4.     <section name="ApplicationSettings" type="System.Configuration.NameValueSectionHandler"/>      
  5.   </configSections>  
  6.     
  7.   <ApplicationSettings>  
  8.     <add key="ApplicationName" value="Configuration Example Project"/>  
  9.     <add key="Language" value="CSharp"/>  
  10.     <add key="SecretKey" value="012345"/>  
  11.   </ApplicationSettings>  
  12.   <startup>  
  13.     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />  
  14.   </startup>    
  15. </configuration>   

To access custom section settings, we first need to find out the section, using GetSection method, which is defined inside the ConfigurationManager class and cast the return value as NameValueCollection. It will return all the keys available inside this custom section and based on the keys, we can get the values easily, as shown below. 

  1. //Approach Two  
  2.         public static void GetConfigurationUsingSection()  
  3.         {  
  4.             var applicationSettings = ConfigurationManager.GetSection("ApplicationSettings") as NameValueCollection;  
  5.             if (applicationSettings.Count == 0)  
  6.             {  
  7.                 Console.WriteLine("Application Settings are not defined");  
  8.             }  
  9.             else  
  10.             {  
  11.                 foreach (var key in applicationSettings.AllKeys)  
  12.                 {  
  13.                     Console.WriteLine(key + " = " + applicationSettings[key]);  
  14.                 }  
  15.             }  
  16.         }   

When we implement the code given abbove, we get the output given below.


Third approach 

Now, let's move to some tough stuff. Here, we are going to create a section inside the group, so that, if required, we can add multiple sections in the same group. It is basically grouping the same type of section in a group.

In the example given below, we have created one group named BlogGroup and inside it, we have defined one section, named it “PostSetting” and its type as a NameValueSectionHandler. “PostSetting” section contains all the key/value pair separately, as shown below. 

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <configuration>  
  3.   <configSections>     
  4.     <sectionGroup name="BlogGroup">  
  5.       <section name="PostSetting" type="System.Configuration.NameValueSectionHandler"/>  
  6.     </sectionGroup>  
  7.     <section name="ProductSettings" type="ConfigurationExample.ProductSettings, ConfigurationExample"/>  
  8.   </configSections>  
  9.   
  10.   <BlogGroup>  
  11.     <PostSetting>  
  12.       <add key="PostName" value="Getting Started With Config Section in .Net"/>  
  13.       <add key="Category" value="C#"></add>  
  14.       <add key="Author" value="Mukesh Kumar"></add>  
  15.       <add key="PostedDate" value="28 Feb 2017"></add>  
  16.     </PostSetting>  
  17.   </BlogGroup>  
  18.     
  19.   <ProductSettings>  
  20.     <DellSettings ProductNumber="20001" ProductName="Dell Inspiron" Color="Black" Warranty="2 Years" ></DellSettings>  
  21.   </ProductSettings>  
  22.     
  23.   <startup>  
  24.     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>  
  25.   </startup>  
  26. </configuration>   

To read these types of configuration settings, we need to access the section. Based on the section group, we can get all the keys and their values, as shown below.

  1. //Approach Three  
  2.         public static void GetConfigurationUsingSectionGroup()  
  3.         {  
  4.             var PostSetting = ConfigurationManager.GetSection("BlogGroup/PostSetting") as NameValueCollection;  
  5.             if (PostSetting.Count == 0)  
  6.             {  
  7.                 Console.WriteLine("Post Settings are not defined");  
  8.             }  
  9.             else  
  10.             {  
  11.                 foreach (var key in PostSetting.AllKeys)  
  12.                 {  
  13.                     Console.WriteLine(key + " = " + PostSetting[key]);  
  14.                 }  
  15.             }  
  16.         }   

When we implement the code given above, we get the output, as shown below.


Fourth approach 

At last, we are on an advanced stage of the configuration settings. Sometimes, it is required to set up your all key/value pairs based on the custom class behavior, so that we can control the behavior from outside.

See the following class “DellFeatures”, which shows some custom properties of Dell laptops and we need to add it inside the configuration section. The following class contains some default values, if the value is not available in the configuration section.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Configuration;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace ConfigurationExample  
  9. {  
  10.     public class DellFeatures : ConfigurationElement  
  11.     {  
  12.         [ConfigurationProperty("ProductNumber", DefaultValue = 00000, IsRequired = true)]  
  13.         public int ProductNumber  
  14.         {  
  15.             get  
  16.             {  
  17.                 return (int)this["ProductNumber"];  
  18.             }  
  19.             set  
  20.             {  
  21.                 value = (int)this["ProductNumber"];  
  22.             }  
  23.         }  
  24.   
  25.         [ConfigurationProperty("ProductName", DefaultValue = "DELL", IsRequired = true)]  
  26.         public string ProductName  
  27.         {  
  28.             get  
  29.             {  
  30.                 return (string)this["ProductName"];  
  31.             }  
  32.             set  
  33.             {  
  34.                 value = (string)this["ProductName"];  
  35.             }  
  36.         }  
  37.   
  38.         [ConfigurationProperty("Color", IsRequired = false)]  
  39.         public string Color  
  40.         {  
  41.             get  
  42.             {  
  43.                 return (string)this["Color"];  
  44.             }  
  45.             set  
  46.             {  
  47.                 value = (string)this["Color"];  
  48.             }  
  49.         }  
  50.         [ConfigurationProperty("Warranty", DefaultValue = "1 Years", IsRequired = false)]  
  51.         public string Warranty  
  52.         {  
  53.             get  
  54.             {  
  55.                 return (string)this["Warranty"];  
  56.             }  
  57.             set  
  58.             {  
  59.                 value = (string)this["Warranty"];  
  60.             }  
  61.         }  
  62.     }  
  63. }  

To return this setting, we are going to create one more class, which returns this as a property. Here, we can also add multiple classes as the properties.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Configuration;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace ConfigurationExample  
  9. {  
  10.     public class ProductSettings : ConfigurationSection  
  11.     {  
  12.         [ConfigurationProperty("DellSettings")]  
  13.         public DellFeatures DellFeatures  
  14.         {  
  15.             get  
  16.             {  
  17.                 return (DellFeatures)this["DellSettings"];  
  18.             }  
  19.             set  
  20.             {  
  21.                 value = (DellFeatures)this["DellSettings"];  
  22.             }  
  23.         }  
  24.     }  
  25. }  

To implement it inside the configuration section, we are going to change the type of “ProductSettings” as “ConfigurationExample.ProductSettings”, which will return all the properties of DellFeatures class.

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <configuration>  
  3.   <configSections>     
  4.       
  5.     <section name="ProductSettings" type="ConfigurationExample.ProductSettings, ConfigurationExample"/>  
  6.   </configSections>  
  7.   
  8.   <BlogGroup>  
  9.     <PostSetting>  
  10.       <add key="PostName" value="Getting Started With Config Section in .Net"/>  
  11.       <add key="Category" value="C#"></add>  
  12.       <add key="Author" value="Mukesh Kumar"></add>  
  13.       <add key="PostedDate" value="28 Feb 2017"></add>  
  14.     </PostSetting>  
  15.   </BlogGroup>  
  16.     
  17.   <ProductSettings>  
  18.     <DellSettings ProductNumber="20001" ProductName="Dell Inspiron" Color="Black" Warranty="2 Years" ></DellSettings>  
  19.   </ProductSettings>  
  20.     
  21.   <startup>  
  22.     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>  
  23.   </startup>  
  24. </configuration>  

To access this type of configuration, we need to get the custom section first and the rest of it will be accessible very easily, as shown below.

  1. //Approach Four  
  2.         public static void GetConfigurationUsingCustomClass()  
  3.         {  
  4.             var productSettings = ConfigurationManager.GetSection("ProductSettings") as ConfigurationExample.ProductSettings;  
  5.             if (productSettings == null)  
  6.             {  
  7.                 Console.WriteLine("Product Settings are not defined");  
  8.             }  
  9.             else  
  10.             {  
  11.                 var productNumber = productSettings.DellFeatures.ProductNumber;  
  12.                 var productName = productSettings.DellFeatures.ProductName;  
  13.                 var color = productSettings.DellFeatures.Color;  
  14.                 var warranty = productSettings.DellFeatures.Warranty;  
  15.   
  16.                 Console.WriteLine("Product Number = " + productNumber);  
  17.                 Console.WriteLine("Product Name = " + productName);  
  18.                 Console.WriteLine("Product Color = " + color);  
  19.                 Console.WriteLine("Product Warranty = " + warranty);  
  20.             }  
  21.         }  

When we implement the code given above, we get the output, as shown below.


We have seen different ways to define the configuration setting inside the configuration file and access/read it.

I hope this post helps you. Please give your feedback, which will help me to improve the next post. If you have any doubts, please ask your query in the comment section.