1. 使用<appSettings>
        简单的配置信息,可以直接放入<appSettings>标记中。如:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="LogFile" value="d:\log\debug.log"/>
</appSettings>
</configuration>

相应访问代码如下:

string fileName = System.Configuration.ConfigurationSettings.AppSettings.Get("LogFile");

2. 自定义配置节(section)名称
        比如,我们要使用下面的配置结构,将配置信息归类分组:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!-- 需要在此处加入自定义配置声明 -->
<!-- 以下是自定义配置的内容 -->
<myConfig>
<myDictionary>
<add key="Area" value="Fuzhou"/>
<add key="Device" value="Printer"/>
<add key="Customer" value="Muf"/>
</myDictionary>
<myNameValue>
<add key="Area" value="Fuzhou"/>
<add key="Device" value="Printer"/>
<add key="Customer" value="Muf"/>
</myNameValue>
<myInfo Area="Fuzhou" Device="Printer" Customer="Muf" />
</myConfig>
</configuration>

但是光这样子说明是不行的。没有声明是不能使用自定义的配置段。我们必须要在配置文件前面加入声明:

<!-- 以下是自定义配置的声明 -->
<configSections>
<sectionGroup name="myConfig">
<section name="myDictionary"
type="System.Configuration.NameValueSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="myNameValue"
type="System.Configuration.DictionarySectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="myInfo"
type="System.Configuration.SingleTagSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</sectionGroup>
</configSections>
type="System.Configuration.NameValueSectionHandler, System
type含义是代表处理的类名是system命名空间下configuration下的NameValueSectionHandle类,它所在程序集是system

声明和配置的关系,示意图如下:
        
    可以看出,NameValueSectionHandler和DictionarySectionHandler在定义配置文件的内容形式上是一样的,都用<add>来设置内容的。只是返回到C#中的类不太一样
    另外,如果不关心Handler类的版本等信息,可以直接省略。如NameValueSectionHandler可以直接如下声明:

<section name="myDictionary"            type="System.Configuration.NameValueSectionHandler, System" />

把上面的<configSections>声明段放入配置文件中,我们的配置结构就可以正常使用了。声明中,< sectionGroup>用来定义不含配置数据的节的名称。<section>用来定义含有自定义配置数据的节的名称。< section type>用来指定定义配置数据的类型。

    注意,自定义的配置节,不能使用 System.Configuration.ConfigurationSettings.AppSettings.Get 来访问,要使用 System.Configuration.ConfigurationSettings.GetConfig。

    .NET已经定义了3种配置类型:
  a. NameValueSectionHandler

NameValueCollection myNameValue= (NameValueCollection)System.Configuration.ConfigurationSettings.GetConfig(@"myConfig/myNameValue");
string Area = myNameValue["Area"];
string Device= myNameValue["Device"];
string Customer = myNameValue["Customer "];

b. DictionarySectionHandler

Hashtable myNameValue= (Hashtable)System.Configuration.ConfigurationSettings.GetConfig(@"myConfig/myDictionary");
string Area = myNameValue["Area"];
string Device= myNameValue["Device"];
string Customer = myNameValue["Customer "];

c. SingleTagSectionHandler

Hashtable myNameValue= (Hashtable)System.Configuration.ConfigurationSettings.GetConfig(@"myConfig/myInfo");
string Area = myNameValue["Area"];
string Device= myNameValue["Device"];
string Customer = myNameValue["Customer "];

这三种类型的详细信息可以参考 MSDN 文档。同时.NET 还定义了IgnoreSectionHandler类型,为 System.Configuration 之外的系统所读取和处理的配置节提供节处理程序定义。
        除此之外,.NET提供了IConfigurationSectionHandler接口,这样我们还可以自行进行扩展,以设计出我们自已的配置形式。如下例

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!-- 以下是自定义配置的声明 -->
<configSections>
<section name="myConfig" type="myNamespace.MyInfoSectionHandler, myApp" />
</configSections>
<myConfig>
<myInfo Area="Fuzhou" Device="Printer" Customer="Muf" />
<myInfo Area="Shanghai" Device="Mobile" Customer="Liny" />
</myConfig>
</configuration>

myConfig部分的内容Framework不能自动去解析,所以我们需要用下面的代码自己实现解析,此处解析到hashtable中了,原本是xmlnode

public class MyInfoSectionHandler: IConfigurationSectionHandler
{
public object Create(object parent, object configContext, System.Xml.XmlNode section)
{
Hashtable config = new Hashtable();
foreach(XmlNode node in section.ChildNodes)
{
if(node.Name != "myInfo")
throw new System.Configuration.ConfigurationException("不可识别的配置项", node); Hashtable item = new Hashtable();
foreach(XmlAttribute attr in node.Attributes)
{
switch(attr.Name)
{
case "Area":
case "Device":
case "Customer":
item.Add(attr.Name, attr.Value);
break;
default:
throw new System.Configuration.ConfigurationException("不可识别的配置属性", attr);
}
}
config.Add(item["Area"], item);
}
return config;
}
}

使用GetConfig进行配置文件读取。

Hashtable cfgTable = (Hashtable)ConfigurationSettings.GetConfig( "myConfigs" );

Debug.Assert( cfgTable.Count == );
Hashtable cfgFuzhou = (Hashtable)cfgTable["Fuzhou"];
Hashtable cfgShanghai = (Hashtable)cfgTable["Shanghai"];
Debug.Assert( cfgFuzhou["Device"] == "Printer" );
Debug.Assert( cfgShanghai["Device"] == "Mobile" );
Debug.Assert( cfgFuzhou["Customer"] == "Muf" );
Debug.Assert( cfgShanghai["Customer"] == "Liny" ); foreach(Hashtable cfg in cfgTable.Values)
{
Console.WriteLine("Area={0} Device={1} Customer={2}", cfg["Area"], cfg["Device"], cfg["Customer"]);
}

执行过程:首先ConfigurationSettings的GetConfig方法会去驱动Framework把App.config中名称为myconfig节点内容读取到一个XML的Node里面(实际运用中,我们可以不返回XML节点,而返回自定义的存储结构这样使用起来就更方便,所以代码把它解析到hashtable中)。之后Framework会去自动地调用App.config文件中configSections下标签名即name=myconfig的type下类的Create方法。

NET基础课--配置文件2的更多相关文章

  1. NET基础课--配置文件1

    在.NET Framework中,配置几乎是无处不在的.配置是控制应用程序行为的一些设置.下面我们就来看看到底有几个配置文件,而他们又分别代表了什么? 1. machine.config 这个文件只有 ...

  2. .Net Core MVC 网站开发(Ninesky) 2.3、项目架构调整(续)-使用配置文件动态注入

    上次实现了依赖注入,但是web项目必须要引用业务逻辑层和数据存储层的实现,项目解耦并不完全:另一方面,要同时注入业务逻辑层和数据访问层,注入的服务直接写在Startup中显得非常臃肿.理想的方式是,w ...

  3. ASP.NET MVC5+EF6+EasyUI 后台管理系统(64)-补充WebApi与Unity注入-配置文件

    系列目录 上一篇演示了WebApi利用Unity注入 很多人问我如何用配置文件来配置注入,本节演示如何利用配置文件来注入,道理是一样的,跳转到上一节下载源码一起来动手! 1.打开源码定位到文件Depe ...

  4. Spring配置文件标签报错:The prefix "XXX" for element "XXX:XXX" is not bound. .

    例如:The prefix "context" for element "context:annotation-config" is not bound. 这种 ...

  5. nginx服务器安装及配置文件详解

    nginx在工作中已经有好几个环境在使用了,每次都是重新去网上扒博客,各种编译配置,今天自己也整理一份安装文档和nginx.conf配置选项的说明,留作以后参考.像负载均衡配置(包括健康检查).缓存( ...

  6. C#开发中使用配置文件对象简化配置的本地保存

    C#开发中使用配置文件对象简化配置的本地保存 0x00 起因 程序的核心是数据和逻辑,开发过程中免不了要对操作的数据进行设置,而有些数据在程序执行过程中被用户或程序做出的修改是应该保存下来的,这样程序 ...

  7. 使用T4模板生成不同部署环境下的配置文件

    在开发企业级应用的时候,通常会有不同的开发环境,比如有开发环境,测试环境,正式环境,生产环境等.在一份代码部署到不同环境的时候,不同环境的配置文件可能需要根据目标环境不同而不同.比如在开发环境中,数据 ...

  8. 配置文件Java读写

    今天把配置文件的Bug修复了,总结一下Java配置文件如何读写 配置文件的格式 以.properties后缀结尾,内容不出现空格和双引号 //config.properties Driver=com. ...

  9. .NET平台开源项目速览(1)SharpConfig配置文件读写组件

    在.NET平台日常开发中,读取配置文件是一个很常见的需求.以前都是使用System.Configuration.ConfigurationSettings来操作,这个说实话,搞起来比较费劲.不知道大家 ...

随机推荐

  1. E514:write error(file system full?)

    vi编辑某文件,保存时报错,提示:E514: write error (file system full?)---写入错误,磁盘满了? 查看磁盘空间:df -h根目录磁盘空间已满,used%100. ...

  2. flashback database操作步骤

    默认情况数据库的flashback database是关闭的. 启用Flashback Database 步骤:1.配置Flash Recovery Area 检查是否启动了flash recover ...

  3. [HeadFirst-HTMLCSS学习笔记][第十二章HTML5标记]

    考虑HTML结构 HTML5即是把原来<div>换成一些更特定的元素.能够更明确指示包含什么内容. (页眉,导航,页脚,文章) article nav 导航 header footer t ...

  4. C#遍历获取枚举的值,名和属性

    获取: Type type = typeof(ParamServiceType); var values = Enum.GetValues(type); ; i < values.Length; ...

  5. 父元素高度为auto,子元素使用top:-50%没有效果的问题

    无意间在实现元素垂直居中的一种方式测试到,当一个元素高度没有指定的情况下,其 postion:relative;top:-50%;无效 后来查阅w3c看到这样一句话: <percentage&g ...

  6. doT.js 声明

    // 模板引擎配置项 var tmplOptions = { evaluate: /\{\{([\s\S]+?\}?)\}\}/g, interpolate: /\{\{=([\s\S]+?)\}\} ...

  7. jquery怎么获取URL的参数

    function request(paras) {                var url = location.href;                var paraString = ur ...

  8. Sql语句不能识别Go的解决办法(动态创建表的触发器)

    问题来源 用sqlserver直接打开sql文本,执行没问题,但是当用Sqlcommand类执行cmdtext命令文本时总是失败报错. 原因分析及解决 用数据库直接执行sql语句没问题,甚至还可以用G ...

  9. struts2 注解方式

    struts2扫描方法: 扫描其位于包的命名注解的类 “struts, struts2, action 或 actions“. 接着,扫描相匹配下列任一条件的文件: 实例了 com.opensymph ...

  10. Linux 入门命令

    本文系转载:http://www.cnblogs.com/wwj9413/archive/2012/03/15/2638638.html#2929949 1.Linux进入与退出系统 进入Linux系 ...