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 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.

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 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.

public static void GetConfigurationUsingSection()
{
var applicationSettings = ConfigurationManager.GetSection("ApplicationSettings")
as NameValueCollection; if (applicationSettings.Count == )
{
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 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="" 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.

public static void GetConfigurationUsingSectionGroup()
{
var PostSetting = ConfigurationManager.GetSection("BlogGroup/PostSetting") as NameValueCollection;
if (PostSetting.Count == )
{
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.

 
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 = , 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.

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 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="" 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.

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.

Four Ways to Read Configuration Setting in C#(COPY)的更多相关文章

  1. maven setting.xml 配置(有效)

    <?xml version="1.0" encoding="UTF-8"?> <settings xmlns="http://mav ...

  2. System Center Configuration Manager 2016 配置安装篇(Part3)

    SCCM 2016 配置管理系列(Part 1- 4) 介绍AD01上配置了Active Directory域服务(ADDS),然后将Configuration Manager服务器(CM16)加入到 ...

  3. System Center Configuration Manager 2016 配置安装篇(Part1)

    SCCM 2016 配置管理系列(Part 1- 4) 介绍AD01上配置了Active Directory域服务(ADDS),然后将Configuration Manager服务器(CM16)加入到 ...

  4. System Center Configuration Manager 2016 必要条件准备篇(Part1)

    步骤4.创建系统管理容器 SCCM 2016 配置管理系列(Part 1- 4) 介绍AD01上配置了Active Directory域服务(ADDS),然后将Configuration Manag ...

  5. System Center Configuration Manager 2016 域准备篇(Part4)

    步骤4.创建系统管理容器 注意:在Active Directory域控制器服务器(AD01)上以本地管理员身份执行以下操作 有关您为何这样做的详细信息,请参阅https://docs.microsof ...

  6. 微软企业库5.0 学习之路——第八步、使用Configuration Setting模块等多种方式分类管理企业库配置信息

    在介绍完企业库几个常用模块后,我今天要对企业库的配置文件进行处理,缘由是我打开web.config想进行一些配置的时候发现web.config已经变的异常的臃肿(大量的企业库配置信息充斥其中),所以决 ...

  7. Spark 官方文档(4)——Configuration配置

    Spark可以通过三种方式配置系统: 通过SparkConf对象, 或者Java系统属性配置Spark的应用参数 通过每个节点上的conf/spark-env.sh脚本为每台机器配置环境变量 通过lo ...

  8. maven -- 学习笔记(二)之setting.xml配置说明(备忘)

    setting.xml配置说明,learn from:http://pengqb.javaeye.com,http://blog.csdn.net/mypop/article/details/6146 ...

  9. maven之(六)setting.xml的配置文件详解

    setting.xml配置文件 maven的配置文件settings.xml存在于两个地方: 1.安装的地方:${M2_HOME}/conf/settings.xml 2.用户的目录:${user.h ...

随机推荐

  1. Qt 信号和槽异常: QObject::connect: No Such slot baseClassName::subClassfunction() in ......

    2019-08-14起笔 小熊的情况描述: 父类A继承自QWidget,所以父类A自动添加了Q_OBJECT.  子类B继承自父类A,子类B没有添加Q_OBJECT.在子类B中给动态创建的控件添加事件 ...

  2. nginx如何实现负载均衡以及实现方式

    什么是ngnix? Nginx是一个http服务器.是一个使用c语言开发的高性能的http 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器.nginx能够支撑5万并发链接,并且cpu ...

  3. MIT / BSD / Apache / LGPL / Mozilla / GPL 区别

    自由度:MIT > BSD > Apache > LGPL > Mozilla > GPL

  4. ArrayList和LinkedList介绍

    java.util.ArrayList集合的数据存储结构是数组,且是多线程,元素增删慢,查找快, 由于日常使用开发大多数为查询数据,遍历数据,所以ArrayList是最常用的集合.上一节已写了. ja ...

  5. springcloud Springboot vue.js Activiti6 前后分离 跨域 工作流 集成代码生成器 shiro权限

    1.代码生成器: [正反双向](单表.主表.明细表.树形表,快速开发利器)freemaker模版技术 ,0个代码不用写,生成完整的一个模块,带页面.建表sql脚本.处理类.service等完整模块2. ...

  6. vue-svgicon基本使用

    在项目开发中,经常会用到svg图标,之前用的都是vue-svg-icon,最近在npm中搜索svg图标解析插件,发现vue-svgicon用的相对较多,对比以下,vue-svgicon用法较为灵活,方 ...

  7. echarts 柱状图+折线+文字倾斜及省略

    效果图: 代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...

  8. JS基础语法---作用域链

    从函数嵌套来分析: (层数一般5层内) var num=10; function f1() { var num=20; function f2() { var num=30; function f3( ...

  9. SAP MM 无料号采购申请单中'评估价格'之填写

    SAP MM 无料号采购申请单中'评估价格'之填写 1),SAP系统中,采购申请里的'评估价格'来源有二, a)如果是有物料号的采购,则该价格来自于物料主数据里里的成本价(移动平均价或者标准价),自动 ...

  10. 微信小程序之文件系统初探

    微信小程序之文件系统初探 1.文件下载 //下载文件 go_download: function() { var content = this; var baseUrl = "http:// ...