在日常的程序设计中,如何灵活和巧妙地运用配置信息是一个成功的设计师的首要选择。这不仅是为了程序设计得更灵活性和可扩展性,也是为了让你的代码给人以清新的感觉。程序中的配置信息一般放在应用程序的app.config或web.config文件中,当然也可以自定义自己的配置文件。这些配置文件是以XML格式进行存储和读取的。微软也封装一些对这些配置文件操作的类,这些类存在于名字空间System.Configuration下,这个命名空间包含提供用于处理配置数据的编程模型的类型,当然为了使用还添加System.Configuration.dll程序集。

现在我们先看一下这个名字空间下的几个重要的类:

1、ConfigurationManager,这个提供用于打开客户端应用程序集的Configuration对象。

2、WebConfigurationMaManager,这个提供用于打开web应用程序集的Configuration对象。

3、ConfigurationSection ,表示配置文件中的节。

4、ConfigurationSectionCollection ,表示配置文件中相关节的集合。

5、ConfigurationSectionGroup ,表示配置文件中的一组相关节。

6、ConfigurationSectionGroupCollection ,表示 ConfigurationSectionGroup 对象的集合。

7、ConfigurationProperty ,表示属性或配置元素的子元素。

8、ConfigurationPropertyAttribute ,以声明方式指示 .NET Framework,以实例化配置属性。

9、ConfigurationElement ,表示配置文件中的配置元素。

10、ConfigurationElementCollection ,表示包含一个子元素集合的配置元素。

当然这里面这常用的是ConfigurationManager类,这个类提供了两个静态常用的静态方法:

object GetSection(string sectionName)用于读取当前应用程序默认配置的指定配置信息;

Configuration OpenExeConfiguration(ConfigurationUserLevel userLevel)将当前应用程序配置文件打开以得到一个Configuration对象。

以及两个静态属性:AppSettins获取当前应用程序默认配置的AppSettingsSection数据;ConnectionStrings获取当前应用程序默认配置的ConnectionStringSection数据。

当然由于AppSettings是一个NameValueCollection对象,因此对它的读取和设置可以直接以AppSettings[“mySet”]的形式得到,相应的在*.config文件中的<appsettings>节下添加<add name=”mySet” value=””/>即可。

要自定义配置节配置元素,就必须要使我们的类分别继承自ConfigurationSection和ConfigurationElement类。那么实现这个两个类的对象就可以加入到配置文件的<configSection>和其他元素节点中。

这儿介绍在配置节点中加入自定义配置信息的能力(元素节点)。

1、实现一个继承自ConfigurationElement和ConfigurationSection的类,并添加的配置属性加上ConfigurationPropertyAttribute特性。

2、添加配置信息。

3、在程序中读取配置信息。

第一步:实现派生自ConfigurationSection和ConfigurationElement的类



Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

-->using System;

using System.Collections;
using System.Text;
using System.Configuration;
using System.Xml;
 
 
namespace MyCustomConfiguration
{
   //自定义配置节
   public class CustomSectionConfiguration : ConfigurationSection
   { 
      public CustomSectionConfiguration() { }
      public CustomSectionConfiguration(string value) { }
      //添加特性ConfigurationPropertyAttribute
      //'customAttribute'是配置文件中的元素
      //'CustomAttribute'是程序中要的属性;
      [ConfigurationProperty("customAttribute", DefaultValue = "", IsRequired = true)]
      public string CustomAttribute
      {
          get { return (string)base["customAttribute"]; }
          set { base["customAttribute"] = value; }
         }
       //添加特性ConfigurationPropertyAttribute
       [ConfigurationProperty("customElement", DefaultValue = "", IsRequired = true)]
       public CustomElementConfiguration CustomElement
        {
           get { return (CustomElementConfiguration)base["customElement"]; }
           set { base["customElement"] = value; }
           }
    }
    
     //自定义配置元素
     public class CustomElementConfiguration : ConfigurationElement
     {
        public CustomElementConfiguration() { }
        public CustomElementConfiguration(string value1, string value2)
        {
            Value1 = value1;
            Value2 = value2;
         }
        [ConfigurationProperty("value1", DefaultValue = "", IsRequired = true)]
        public string Value1
       {
          get { return (string)base["value1"]; }
          set { base["value1"] = value; }
         }
          [ConfigurationProperty("value2", DefaultValue = "", IsRequired = true)]
          public string Value2
          {
             get { return (string)base["value2"];}
              set { base["value2"] = value; }
             }
     }  
 }

第二步:在*.config中设置自定的元素



Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/ --><configuration> <!-- 配置节-->
<configSections>
<sectionGroup name="customGroup">
<section
name="customSection"
type=" MyCustomConfiguration.CustomSectionConfiguration, MyCustomConfiguration, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowLocation="true" allowDefinition="everywhere" />
</sectionGroup> ……
<!-- 配置节设置信息 -->
<customGroup>
<customSection customAttribute="Custom">
<customElement Value1=”best" Vaule2=”better”/>
</customSection>
</customGroup> …… </configuration>

第三步:在程序中使用配置信息。



Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

-->MyCustomConfiguration.CustomSectionConfiguration config = (MyCustomConfiguration.CustomSectionConfiguration)System.Configuration.ConfigurationManager.GetSection( "customGroup/customSection");

首先得到配置节对象:         接着就可以使用强名称的对象和属性了。

上面介绍的是单一属性的配置,如果要配置多个对象,那么就得使用System.Configuration.ConfigurationElementCollection,这类的作用是生成多个子对象,也就是在一个标签下可以放置多个System.Configuration.ConfigurationElement对象。

方法同上,我们必须要重写几方法:

ConfigurationElement CreateNewElement()//这个方法的作用是返回子对象实例;

object GetElementKey(ConfigurationElement element);//这个方法的得到对象中的键名;

ConfigurationElementCollectionType CollectionType{get;}//这个属性是定义映射方式;

string ElementName{get;}//这个属性是定义XML元素的名字。



Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

-->protected override ConfigurationElement CreateNewElement()

{
      
return new CustomElementConfiguration ();
}
protected override object GetElementKey(ConfigurationElement element)
{
     return ((CustomElementConfiguration )element).Name;
  }
public override ConfigurationElementCollectionType CollectionType
  {
            get { return ConfigurationElementCollectionType.BasicMap; }
   
}
protected override string ElementName
{
     get { return "collection"; }
}

C#如何使用和开发自定义配置节的更多相关文章

  1. 基于Spring的可扩展Schema进行开发自定义配置标签支持

    一.背景 最近和朋友一起想开发一个类似alibaba dubbo的功能的工具,其中就用到了基于Spring的可扩展Schema进行开发自定义配置标签支持,通过上网查资料自己写了一个demo.今天在这里 ...

  2. C#创建自定义配置节

    在.Net应用程序中,我们经常看到VS为我们生成的项目工程中都会含有nfig或者nfig这样的文件.这个文件就是我们所说的应用程序配置文件.在这个文件里面记述着一些与我们的应用程序相关的信息,如:数据 ...

  3. 使用 ConfigurationSection 创建自定义配置节

    我们可以通过用自己的 XML 配置元素来扩展标准的 ASP.NET 配置设置集,要完成这一功能,我们必须实现继承System.Configuration.ConfigurationSection 类来 ...

  4. C# App.config 自定义 配置节

    1)App.config <?xml version="1.0" encoding="utf-8" ?><configuration>  ...

  5. C# App.config 自定义 配置节 报错“配置系统未能初始化” 解决方法

    App.config,结果运行的时候出现了 "配置系统未能初始化" 的错误.找了半天才发现是下面的原因造成的: "如果配置文件中包含configSections元素,则c ...

  6. .NET:自定义配置节

    背景 对于编译型应用程序来说,参数化程序行为是非常有必要的,.NET有其标准的配置方法,我们可以可以扩展. 示例 代码 using System; using System.Collections; ...

  7. C# App.config 自定义 配置节 出现的问题:配置系统未能初始化

    C# 读取app.config配置文件 节点键值,提示 "配置系统未能初始化" 错误的解决方案 新建C#项目,在app.config中添加了appSettings项,运行时出现&q ...

  8. ASP.NET使用ConfigurationSection在Web.Config创建自定义配置节集合

    核心代码 using System; using System.Data; using System.Configuration; using System.Web; using System.Web ...

  9. ASP.NET使用ConfigurationSection在Web.Config创建自定义配置节

    主要代码,一定要继续System.Configuration.ConfigurationSection,具体的节点名称可以自行修改 using System; using System.Data; u ...

随机推荐

  1. dbt

    Procedure Relocate(s : state; b : base_index) { Move base for state s to a new place beginning at b ...

  2. Objective-C常用类型、对象、方法

    结构体 NSRange range=NSMakeRange(8,10);从0数第八个元素开始长度为10: NSString *str=NSStringFormRange(range); NSLog(@ ...

  3. fedora 解决yumBackend.py进程CPU占用过高

    fedora启动时电脑风扇噪声巨响,检查进行发现是yumBackend.py进行占用CPU过高. yumBackend.py进行是后台检查更新,如果觉得没用可以使用工具关闭检查更新,或者修改检查周期. ...

  4. ORA-15025: could not open disk 处理

    刚才下班回家的路上,接到客户的电话:"回家了吗?我们这边的一套RAC库有个节点有问题哦,一直刷异常,一下子就把磁盘弄满了,我现在停掉了那个节点了.从日志上看好像跟权限有关,现在还有个实例跑着 ...

  5. 【BZOJ 1295】 [SCOI2009]最长距离

    Description windy有一块矩形土地,被分为 N*M 块 1*1 的小格子. 有的格子含有障碍物. 如果从格子A可以走到格子B,那么两个格子的距离就为两个格子中心的欧几里德距离. 如果从格 ...

  6. sql shard/partition

    sql http://www.infoq.com/news/2011/02/SQL-Sharding/ http://channel9.msdn.com/Shows/Data-Exposed/SqlD ...

  7. CLSID {91493441-5A91-11CF-8700-00AA0060263B}错误

    最近遇到一个棘手的问题,在C#中处理PPT转HTML的过程中需要用到COM组件,按照往常的设置如下: 1. Start->Run->DCOMCNFG->Component Servi ...

  8. Mvc设计模型与三层架构

    Mvc(Model-View-Controller):是软件架构的一中设计模式,对软件进行分割成3个层次:视图.模型.控制. 实现对软件的一种动态的设计,并且容易对软件进行扩展.后期的修改,使某些程序 ...

  9. 浅谈JavaSccript函数与对象

    函数 解剖函数 function One(leve1 , leve2){ //code return leve1+leve2 } 注释: 形参不需要加上类型: return语句为可选,没有return ...

  10. 这是我用Microsoft Word 2010 直接发布的测试用博客

    目的:如题所示.   那么先试试拷贝一段网页内容,发布后观察各种格式的显示效果如何. 下面的文字来自中国网新闻,地址是http://news.china.com.cn/2015-10/23/conte ...