一个web.Config或app.Config自定义段configSections的示例

一个web.Config或app.Config自定义段configSections的示例

越来越觉得,直接用配置文件app.Config或web.Config配置应用系统的运行参数,比自己做一个xml配置文件,简洁方便得多。这两个配置文件不仅有常见的connectionStrings和appSettings,给出了数据库连接或常见的名/值表的定义访问方法,而且提供了自定义段configSections,可以自行定义段元素,扩展了appSettings一个段的功能。下面是一个具体的应用实例。

 

1、配置文件(web.Config或app.Config)

 

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

  <configSections> <!-- 该元素必须在 appSettings 之前-->
      <sectionGroup name="Units">
          <section name="国防部" type="System.Configuration.NameValueSectionHandler"/>
          <section name="公安部" type="System.Configuration.NameValueSectionHandler"/>
      </sectionGroup>
  </configSections>

  <Units>
      <国防部>
          <add key="部长名" value="国防部部长"/>
          <add key="副部长" value="国防部次长"/>
    </国防部>


    <公安部>
        <add key="部长名" value="公安部部长"/>
        <add key="副部长" value="公安部次长"/>
    </公安部>
  </Units>

  <appSettings>
      <add key="A1" value="A1Value"/>
      <add key="A2" value="A2Value"/>
  </appSettings>

</configuration>

 

需要指出:

  1. 在configSections中,必须先定义自定义段元素组的组名,即“Units”,然后再定义Units的两个段“国防部”和“公安部”。显然,可以定义段组Units的任意多个段。
  2. 在配置文件中,configSections元素必须在appSettings元素之前,否则将报访问错误。

 

2、访问自定义配置节点

 

      NameValueCollection sections = (NameValueCollection)ConfigurationManager.GetSection("Units/国防部");
      if (sections != null)
      {
           for(int k = 0; k < sections.Keys.Count; k++)
           {
               listBox1.Items.Add(sections.Keys[k] + "  " + sections[k]);
           }
      }

      listBox1.Items.Add(ConfigurationManager.AppSettings["A1"]);
      listBox1.Items.Add(ConfigurationManager.AppSettings["A2"]);

 

在代码中,可以直接使用sections["部长名"]、sections["副部长"]的形式获取key的value值,也可以GetSection("Units/公安部")获取"公安部"段的key和value值。

 

需要指出,在VS 2005的项目中

  • 必须添加引用程序集 System.configuration;
  • 在名称空间添加 using System.Configuration。

本文配置文件和程序代码在VC# 2005和.NET 2.0环境下的窗体项目中编译通过。可以看出,访问自定义段和appSettings段的访问的几乎没有差别,仍然是简洁与直接的。


转载于:https://www.cnblogs.com/kevinGao/p/4188740.html

猜你喜欢

转载自blog.csdn.net/weixin_33860528/article/details/93767137