Read From Multiple Config Files .net C#

This commodity volition demonstrate how we tin 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 ascertain those values inside the configuration section, which might be needed to make it more secure. It can be some underground keys or the value, which should be received frequently.

Today, I will show yous four different ways to become the values from the configuration department.

For this demonstration, I am going to create a unproblematic console Application and provide the name every bit "ConfigurationExample". Just create one console Application, as shown beneath.

New Project > Visual C# > Panel Application

Four Ways To Read Configuration Setting In C#

We need to add Organization.Configuration associates reference to access configuration settings, using ConfigurationManager. To add together the reference, but correct click References and click to add references.

Four Ways To Read Configuration Setting In C#

Now, we can meet that Arrangement.Configuration reference has been added successfully to our projection.

Four Ways To Read Configuration Setting In C#

Thus, allow'southward movement to different ways to add the values within the config file and the approach we follow to become it.

First approach

Let's accept one example, where nosotros need to add some Application level settings and admission them based on their keys. Nosotros tin can add these settings either inside Web.Config or App.Config only nosotros need to add <appSettings> section inside the configuration section.

Only follow the example given below, where inside the appSettings department; we take defined few keys and their values.

App.config

          <?xml version="1.0" encoding="utf-viii" ?>   <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 named ConfigurationManager, which has one getter property named AppSettings. We tin merely pass the cardinal inside the AppSettings and become the desired value from AppSettings section, equally shown below.

          public static void GetConfigurationValue()   {       var title = ConfigurationManager.AppSettings["championship"];       var language = ConfigurationManager.AppSettings["language"];       Panel.WriteLine(cord.Format("'{0}' project is created in '{1}' linguistic communication ", title, language));   }                  

When nosotros implement the lawmaking given to a higher place, we get the output, as shown beneath.

Four Ways To Read Configuration Setting In C#

Second approach

Allow'southward move to the next case. If we need to add the settings inside the section for the separation, in this state of affairs, we can create a custom section inside the configuration section in App.Config/Web.Config, every bit 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.

          <?xml version="1.0" encoding="utf-8" ?>   <configuration>      <configSections>       <section name="ApplicationSettings" blazon="Organization.Configuration.NameValueSectionHandler"/>         </configSections>          <ApplicationSettings>       <add together key="ApplicationName" value="Configuration Instance Project"/>       <add key="Language" value="CSharp"/>       <add together fundamental="SecretKey" value="012345"/>     </ApplicationSettings>     <startup>       <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />     </startup>     </configuration>                  

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

          //Approach Two   public static void GetConfigurationUsingSection()   {       var applicationSettings = ConfigurationManager.GetSection("ApplicationSettings") equally 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 nosotros implement the code given abbove, we get the output given beneath.

Four Ways To Read Configuration Setting In C#

Tertiary approach

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

In the instance given below, nosotros have created ane group named BlogGroup and inside information technology, we accept defined i department, named information technology "PostSetting" and its type as a NameValueSectionHandler. "PostSetting" section contains all the key/value pair separately, as shown below.

          <?xml version="1.0" encoding="utf-viii"?>   <configuration>     <configSections>          <sectionGroup name="BlogGroup">         <department proper name="PostSetting" blazon="System.Configuration.NameValueSectionHandler"/>       </sectionGroup>       <section name="ProductSettings" type="ConfigurationExample.ProductSettings, ConfigurationExample"/>     </configSections>        <BlogGroup>       <PostSetting>         <add together key="PostName" value="Getting Started With Config Section in .Net"/>         <add together key="Category" value="C#"></add>         <add key="Writer" value="Mukesh Kumar"></add>         <add cardinal="PostedDate" value="28 Feb 2017"></add together>       </PostSetting>     </BlogGroup>          <ProductSettings>       <DellSettings ProductNumber="20001" ProductName="Dell Inspiron" Colour="Black" Warranty="two Years" ></DellSettings>     </ProductSettings>          <startup>       <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>     </startup>   </configuration>        

To read these types of configuration settings, we demand to access the section. Based on the section group, we tin can become all the keys and their values, as shown beneath.

          //Approach 3   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 fundamental in PostSetting.AllKeys)           {               Console.WriteLine(key + " = " + PostSetting[key]);           }       }   }        

When we implement the code given higher up, we get the output, every bit shown below.

Four Ways To Read Configuration Setting In C#

4th approach

At terminal, we are on an avant-garde phase of the configuration settings. Sometimes, information technology is required to set upwardly your all key/value pairs based on the custom class behavior, so that we tin control the behavior from outside.

Meet the following class "DellFeatures", which shows some custom properties of Dell laptops and we demand to add it inside the configuration section. The post-obit form contains some default values, if the value is not bachelor in the configuration section.

          using System;   using Organisation.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"];               }               gear up               {                   value = (int)this["ProductNumber"];               }           }              [ConfigurationProperty("ProductName", DefaultValue = "DELL", IsRequired = true)]           public cord ProductName           {               become               {                   render (string)this["ProductName"];               }               fix               {                   value = (cord)this["ProductName"];               }           }              [ConfigurationProperty("Color", IsRequired = imitation)]           public cord Colour           {               get               {                   render (string)this["Color"];               }               ready               {                   value = (cord)this["Colour"];               }           }           [ConfigurationProperty("Warranty", DefaultValue = "one Years", IsRequired = imitation)]           public string Warranty           {               get               {                   return (cord)this["Warranty"];               }               set               {                   value = (string)this["Warranty"];               }           }       }   }        

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

          using System;   using Arrangement.Collections.Generic;   using System.Configuration;   using System.Linq;   using System.Text;   using Organization.Threading.Tasks;      namespace ConfigurationExample   {       public form ProductSettings : ConfigurationSection       {           [ConfigurationProperty("DellSettings")]           public DellFeatures DellFeatures           {               get               {                   render (DellFeatures)this["DellSettings"];               }               set up               {                   value = (DellFeatures)this["DellSettings"];               }           }       }   }        

To implement it inside the configuration section, we are going to alter the blazon of "ProductSettings" equally "ConfigurationExample.ProductSettings", which will return all the properties of DellFeatures grade.

          <?xml version="1.0" encoding="utf-8"?>   <configuration>     <configSections>                 <section proper name="ProductSettings" type="ConfigurationExample.ProductSettings, ConfigurationExample"/>     </configSections>        <BlogGroup>       <PostSetting>         <add together key="PostName" value="Getting Started With Config Section in .Net"/>         <add key="Category" value="C#"></add>         <add fundamental="Author" value="Mukesh Kumar"></add>         <add together key="PostedDate" value="28 Feb 2017"></add>       </PostSetting>     </BlogGroup>          <ProductSettings>       <DellSettings ProductNumber="20001" ProductName="Dell Inspiron" Color="Blackness" Warranty="ii Years" ></DellSettings>     </ProductSettings>          <startup>       <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>     </startup>   </configuration>        

To admission this type of configuration, nosotros need to go the custom section first and the residual of it volition be accessible very easily, equally shown below.

          //Approach Iv   public static void GetConfigurationUsingCustomClass()   {       var productSettings = ConfigurationManager.GetSection("ProductSettings") as ConfigurationExample.ProductSettings;       if (productSettings == null)       {           Console.WriteLine("Product Settings are not divers");       }       else       {           var productNumber = productSettings.DellFeatures.ProductNumber;           var productName = productSettings.DellFeatures.ProductName;           var colour = productSettings.DellFeatures.Color;           var warranty = productSettings.DellFeatures.Warranty;            Console.WriteLine("Production Number = " + productNumber);           Console.WriteLine("Product Proper noun = " + productName);           Console.WriteLine("Production Colour = " + color);           Console.WriteLine("Product Warranty = " + warranty);       }   }        

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

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

I hope this post helps you. Please requite your feedback, which will help me to improve the side by side mail service. If y'all have any doubts, please ask your query in the comment section.

deweyexpet1965.blogspot.com

Source: https://www.c-sharpcorner.com/article/four-ways-to-read-configuration-setting-in-c-sharp/

0 Response to "Read From Multiple Config Files .net C#"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel