.NET开发

本类阅读TOP10

·NHibernate快速指南(翻译)
·vs.net 2005中文版下载地址收藏
·【小技巧】一个判断session是否过期的小技巧
·VB/ASP 调用 SQL Server 的存储过程
·?dos下编译.net程序找不到csc.exe文件
·通过Web Services上传和下载文件
·学习笔记(补)《.NET框架程序设计(修订版)》--目录
·VB.NET实现DirectDraw9 (2) 动画
·VB.NET实现DirectDraw9 (1) 托管的DDraw
·建站框架规范书之——文件命名

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
如何使用.NET配置文件(二)

作者:未知 来源:月光软件站 加入时间:2005-5-13 月光软件站

    3. 自定义配置结构 (使用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来实现任意的配置文件结构。
 
 (待续)




相关文章

相关软件