Click here to Skip to main content
15,885,435 members
Articles / Programming Languages / C#

Four Ways to Read Configuration Setting in C#

Rate me:
Please Sign up or sign in to vote.
4.40/5 (20 votes)
3 Dec 2017CPOL4 min read 105K   51   13
Today I will show you, four different ways to get the values from configuration section.

Introduction

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

Using the code

Today I will show you, four different ways to get the values from 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 following.

Just follow: New Project > Visual C# > Console Application

 

We need to add System.Configuration assembly reference to access configuration setting using ConfigurationManager. To add reference, just right click to References and Click to Add References.

Now we can see that System.Configuration reference added successfully with our project.

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

Approach One

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 setting either inside Web.Config or App.Config. But we need to add <appSettings> section inside the configuration section.

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

App.config

XML
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <appSettings>
    <add key="Title" value="Configuration Example"/>
    <add key="Language" value="CSharp"/>
  </appSettings>
</configuration>

 

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

C#
public static void GetConfigurationValue()
{
      var title = ConfigurationManager.AppSettings["title"];
      var language = ConfigurationManager.AppSettings["language"];

      Console.WriteLine(string.Format("'{0}' project is created in '{1}' language ", title, language));
}

When we implement the above code, we get following out.

 

Approach Two

Let’s move to next example, just think about if we need to add settings inside section for separation. So, in this situation, we can create custom section inside the configuration section in App.Config/Web.Config as following. Section can make your data more readable and understandable based on your section name.

In following example, we have just created one custom section as named “ApplicationSettings” and added all key/value pairs separately.

XML
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="ApplicationSettings" type="System.Configuration.NameValueSectionHandler"/>
  </configSections>

  <ApplicationSettings>
    <add key="ApplicationName" value="Configuration Example Project"/>
    <add key="Language" value="CSharp"/>
    <add key="SecretKey" value="xxxxxxx"/>
  </ApplicationSettings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>

 

To access custom section settings, first we 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 keys we can get values easily as following.

C#
public static void GetConfigurationUsingSection()
{
     var applicationSettings = ConfigurationManager.GetSection("ApplicationSettings") 
        as NameValueCollection;

     if (applicationSettings.Count == 0)
     {
         Console.WriteLine("Application Settings are not defined");
     }
     else
     {
        foreach (var key in applicationSettings.AllKeys)
        {
            Console.WriteLine(key + " = " + applicationSettings[key]);
        }
     }

}

When we implement the above code, we get following out.

 

Approach Three

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

In following example, we have created one group as named “BlogGroup” and inside that we have defined one section as named “PostSetting” and its type as a NameValueSectionHandler. “PostSetting” section is containing all the key/value pair separately as following.

XML
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="BlogGroup">
      <section name="PostSetting" type="System.Configuration.NameValueSectionHandler"/>
    </sectionGroup>
    <section name="ProductSettings" type="ConfigurationExample.ProductSettings, ConfigurationExample"/>
  </configSections>

  <BlogGroup>
    <PostSetting>
      <add key="PostName" value="Getting Started With Config Section in .Net"/>
      <add key="Category" value="C#"></add>
      <add key="Author" value="Mukesh Kumar"></add>
      <add key="PostedDate" value="28 Feb 2017"></add>
    </PostSetting>
  </BlogGroup>

  <ProductSettings>
    <DellSettings ProductNumber="20001" ProductName="Dell Inspiron" Color="Black" Warranty="2 Years" ></DellSettings>
  </ProductSettings>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
  </startup>
</configuration>

 

To read these types of configuration setting, we need to access section based on section group and then we can get all the keys and their values as following code is doing.

C#
public static void GetConfigurationUsingSectionGroup()
{
    var PostSetting = ConfigurationManager.GetSection("BlogGroup/PostSetting") as NameValueCollection;
    if (PostSetting.Count == 0)
    {
        Console.WriteLine("Post Settings are not defined");
    }
    else
    {
        foreach (var key in PostSetting.AllKeys)
        {
            Console.WriteLine(key + " = " + PostSetting[key]);
        }
    }
}

When we implement the above code, we get following out.

 

Approach Four

At last we are on advance stage of configuration settings. Sometimes it is required to setup your all key/value pair based on custom class behavior so that we can control it behavior form outer world.

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

C#
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConfigurationExample
{
    public class DellFeatures : ConfigurationElement
    {
        [ConfigurationProperty("ProductNumber", DefaultValue = 00000, IsRequired = true)]
        public int ProductNumber
        {
            get
            {
                return (int)this["ProductNumber"];
            }
        }

        [ConfigurationProperty("ProductName", DefaultValue = "DELL", IsRequired = true)]
        public string ProductName
        {
            get
            {
                return (string)this["ProductName"];
            }
        }

        [ConfigurationProperty("Color", IsRequired = false)]
        public string Color
        {
            get
            {
                return (string)this["Color"];
            }
        }
        [ConfigurationProperty("Warranty", DefaultValue = "1 Years", IsRequired = false)]
        public string Warranty
        {
            get
            {
                return (string)this["Warranty"];
            }
        }
    }
}

 

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

C#
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConfigurationExample
{
    public class ProductSettings : ConfigurationSection
    {
        [ConfigurationProperty("DellSettings")]
        public DellFeatures DellFeatures
        {
            get
            {
                return (DellFeatures)this["DellSettings"];
            }
        }
    }
}

 

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

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

    <section name="ProductSettings" type="ConfigurationExample.ProductSettings, ConfigurationExample"/>
  </configSections>

  <BlogGroup>
    <PostSetting>
      <add key="PostName" value="Getting Started With Config Section in .Net"/>
      <add key="Category" value="C#"></add>
      <add key="Author" value="Mukesh Kumar"></add>
      <add key="PostedDate" value="28 Feb 2017"></add>
    </PostSetting>
  </BlogGroup>

  <ProductSettings>
    <DellSettings ProductNumber="20001" ProductName="Dell Inspiron" Color="Black" Warranty="2 Years" ></DellSettings>
  </ProductSettings>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
  </startup>
</configuration>

 

To access this type of configuration, same we need to get custom section first and rest of will be accessible very easily as following code.

C#
public static void GetConfigurationUsingCustomClass()
{
    var productSettings = ConfigurationManager.GetSection("ProductSettings") as ConfigurationExample.ProductSettings;
    if (productSettings == null)
    {
        Console.WriteLine("Product Settings are not defined");
    }
    else
    {
        var productNumber = productSettings.DellFeatures.ProductNumber;
        var productName = productSettings.DellFeatures.ProductName;
        var color = productSettings.DellFeatures.Color;
        var warranty = productSettings.DellFeatures.Warranty;

        Console.WriteLine("Product Number = " + productNumber);
        Console.WriteLine("Product Name = " + productName);
        Console.WriteLine("Product Color = " + color);
        Console.WriteLine("Product Warranty = " + warranty);
    }
}

When we implement the above code, we get following out.

Conclusion

So, 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 put your feedback using comment which will help me improve for the next post. If you have any doubts, please ask your doubts or query in the comment section.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
A Software Developer, Microsoft MVP, C# Corner MVP, Blogger and has extensive experience with designing and developing enterprise scale applications on Microsoft .NET Framework.

http://www.mukeshkumar.net
https://www.linkedin.com/in/mukeshkumartech

Comments and Discussions

 
BugApp.config in approach Four is wrong Pin
Member 141079974-Jan-19 5:10
Member 141079974-Jan-19 5:10 
SuggestionApprove 5 Pin
Tommy-White11-Dec-17 19:35
Tommy-White11-Dec-17 19:35 
QuestionExample 4 default value Pin
kelalfbry5-Dec-17 13:33
kelalfbry5-Dec-17 13:33 
QuestionNice article Pin
robertlsharp5-Dec-17 9:57
robertlsharp5-Dec-17 9:57 
AnswerRe: Nice article Pin
MukeshKumarTech13-Dec-17 7:39
MukeshKumarTech13-Dec-17 7:39 
QuestionAn easier way Pin
Sacha Barber4-Dec-17 2:46
Sacha Barber4-Dec-17 2:46 
BugValues should never be exposed in the configuration files!! Pin
Veronica S. Zotali14-Nov-17 0:12
Veronica S. Zotali14-Nov-17 0:12 
GeneralRe: Values should never be exposed in the configuration files!! Pin
Sacha Barber4-Dec-17 2:46
Sacha Barber4-Dec-17 2:46 
QuestionWhy those setters? Pin
Andrej Farkaš28-Feb-17 23:53
Andrej Farkaš28-Feb-17 23:53 
AnswerRe: Why those setters? Pin
MukeshKumarTech1-Mar-17 17:38
MukeshKumarTech1-Mar-17 17:38 
Thanks for your suggestion, I have made changes inside the code. Please have a look.
GeneralRe: Why those setters? Pin
Andrej Farkaš1-Mar-17 19:36
Andrej Farkaš1-Mar-17 19:36 
Questionbunch of your images are missing Pin
BigTimber@home28-Feb-17 10:58
professionalBigTimber@home28-Feb-17 10:58 
AnswerRe: bunch of your images are missing Pin
MukeshKumarTech28-Feb-17 21:13
MukeshKumarTech28-Feb-17 21:13 

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.