自定义配置结构 (使用IConfigurationSectionHandler)
 假设有以下的配置信息,其在MyInfo可以重复许多次,那么应如何读取配置呢?这时就要使用自定义的配置程序了。
<myConfigs>
  <myInfo Area="Fuzhou" Device="Printer" Customer="Muf" />
  <myInfo Area="Shanghai" Device="Mobile" Customer="Liny" />
</myConfig>
访问代码如下:
Hashtable cfgTable = (Hashtable)ConfigurationSettings.GetConfig( "myConfigs" );

Debug.Assert( cfgTable.Count == 2);
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"]);
}
为了能使用上面的访问代码来访问配置结构,我们需要生成一个特定的配置读取类(ConfigurationSectionHandler),例子很简单,就不多做说明了:

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;
 }
}
然后,我们再定义配置说明。其中,myNamespace.MyInfoSectionHandler 是MyInfoSectionHandler类的带名字空间的完整名称;myApp 则是定义MyInfoSectionHandler类的程序集不带扩展名的名字(如myApp.dll或myApp.exe):

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <!-- 以下是自定义配置的声明 -->
  <configSections>
      <section name="myConfig" type="myNamespace.MyInfoSectionHandler, myApp" />
  </configSections> 
  <myConfigs>
    <myInfo Area="Fuzhou" Device="Printer" Customer="Muf" />
    <myInfo Area="Shanghai" Device="Mobile" Customer="Liny" />
  </myConfig>
</configuration>
根据上面的例子,我们可以使用IConfigurationSectionHandler来实现任意的配置文件结构。
转载者注:MyInfoSectionHandler的Create方法实际上是  通过执行ConfigurationSettings.GetConfig方法,才会执行的。

我们要使用下面的配置结构,将配置信息归类分组:

<?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>
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接口,这样我们还可以自行进行扩展,以设计出我们自已的配置形式。

(转).net webconfig使用IConfigurationSectionHandler自定section的更多相关文章

  1. log4net保存到数据库系列一:WebConfig中配置log4net

    园子里面有很多关于log4net保存到数据库的帖子,但是要动手操作还是比较不易,从头开始学习log4net数据库日志 一.WebConfig中配置log4net 二.独立配置文件中配置log4net ...

  2. .Net 自定义应用程序配置

    .Net 自定义应用程序配置 引言 几乎所有的应用程序都离不开配置,有时候我们会将配置信息存在数据库中(例如大家可能常会见到名为Config这样的表):更多时候,我们会将配置写在Web.config或 ...

  3. App.config的学习笔记

    昨天基本弄清config的使用之后,再看WP的API,晕了.结果WP不支持system.configuration命名空间,这意味着想在WP上用App.config不大可能了. WP具体支持API请查 ...

  4. AngularJs + ASP.NET MVC

    [AngularJs + ASP.NET MVC]使用AntularJs快速建立ASP.NET MVC SPA網站 這幾天接觸到了AngularJs的美麗,讓饅頭有點躍躍欲試使用AngularJs來做 ...

  5. App.config

      App.config的学习笔记 昨天基本弄清config的使用之后,再看WP的API,晕了.结果WP不支持system.configuration命名空间,这意味着想在WP上用App.config ...

  6. 打造属于你的提供者(Provider = Strategy + Factory Method) 设计模式 - Provider Pattern(提供者模式)

    打造属于你的提供者(Provider = Strategy + Factory Method)   1.1.1 摘要 在日常系统设计中,我们也许听说过提供者模式,甚至几乎每天都在使用它,在.NET F ...

  7. Elasticsearch:search template

    我们发现一些用户经常编写了一些非常冗长和复杂的查询 - 在很多情况下,相同的查询会一遍又一遍地执行,但是会有一些不同的值作为参数来查询.在这种情况下,我们觉得使用一个search template(搜 ...

  8. linux中常用的60个命令及作用详解

    Linux 必学的 60 个命令 Linux 提供了大量的命令,利用它可以有效地完成大量的工作,如磁盘操作.文件存取.目录操作.进程管理.文件权限设定等.所以,在 Linux 系统上工作离不开使用系统 ...

  9. Elasticsearch系列---几个高级功能

    概要 本篇主要介绍一下搜索模板.映射模板.高亮搜索和地理位置的简单玩法. 标准搜索模板 搜索模板search tempalte高级功能之一,可以将我们的一些搜索进行模板化,使用现有模板时传入指定的参数 ...

随机推荐

  1. MSSQL只能访问特定的数据库

    让用户只能访问特定的数据库(MSSQL) 背景 客户的SQL Server实例上有多个厂商的数据库,每个数据库由各自的进行厂进行商维护, 为了限定不同厂商的维护人员只能访问自己的数据库,现需要给各个厂 ...

  2. ** poj Y2K Accounting Bug 2586

    Y2K Accounting Bug Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 10117   Accepted: 50 ...

  3. Oracle Instanc Client安装命令工具

    条件 1.Linux RHEL 6.X X86_64操作系统 2.从安装Oracleserver的server此次收购Oracle相关文件(同OS) 软件下载 从Oracle包: 1)  instan ...

  4. Zygote过程【3】——SystemServer诞生

    欢迎转载.转载请注明:http://blog.csdn.net/zhgxhuaa 在ZygoteInit的main()方法中做了几件大事.当中一件便是启动Systemserver进程.代码例如以下: ...

  5. Datatable转换为Json 然后,Json数据导入 js 档

    C#在里面Datatable转换为Json的5代码示例 /// <summary> /// Datatable转换为Json /// </summary> /// <pa ...

  6. hdu 1298 T9(特里+DFS)

    pid=1298" target="_blank" style="">题目连接:hdu 1298 T9 题目大意:模拟手机打字的猜想功能.依据概 ...

  7. 【PLSQL】变量声明,结构语句,cursor游标

    ************************************************************************   ****原文:blog.csdn.net/clar ...

  8. TCP与UDP的侵略性

    HTTP必须执行在TCP上吗?SSL必须执行在TCP上吗?...实际上HTTP并没有规定一定要执行在TCP上,甚至FTP也不一定要执行在TCP上!HTTP或者FTP仅仅是说底层信道要保证数据的按序传输 ...

  9. bat(批处理文件)初步 第一篇 基本符号

    近期我使用的一款软件中须要大量的环境变量设置,而我又不想讲这些变量都加入到系统的环境变量中,一方面是由于有一些同名的库文件的版本号却不一样,都 写在系统环境中会相互干扰:还有一方面则是大部分的路径仅仅 ...

  10. 微软系统工具套件SysinternalsSuite各个工具功能说明

    下载地址:http://download.sysinternals.com/files/SysinternalsSuite.zip 工具名    工具说明 Accesschk      Windows ...