3. 自定义配置结构 (使用IConfigurationSectionHandler)
假设有以下的配置信息,其在MyInfo可以重复许多次,那么应如何读取配置呢?这时就要使用自定义的配置程序了。
1<myconfigs>
2<myinfo area="Fuzhou" customer="Muf" device="Printer"></myinfo>
3<myinfo area="Shanghai" customer="Liny" device="Mobile"></myinfo>
4
5访问代码如下:
6Hashtable cfgTable = (Hashtable)ConfigurationSettings.GetConfig( "myConfigs" );
7
8Debug.Assert( cfgTable.Count == 2);
9Hashtable cfgFuzhou = (Hashtable)cfgTable["Fuzhou"];
10Hashtable cfgShanghai = (Hashtable)cfgTable["Shanghai"];
11Debug.Assert( cfgFuzhou["Device"] == "Printer" );
12Debug.Assert( cfgShanghai["Device"] == "Mobile" );
13Debug.Assert( cfgFuzhou["Customer"] == "Muf" );
14Debug.Assert( cfgShanghai["Customer"] == "Liny" );
15
16foreach(Hashtable cfg in cfgTable.Values)
17{
18Console.WriteLine("Area={0} Device={1} Customer={2}", cfg["Area"], cfg["Device"], cfg["Customer"]);
19}
20
21为了能使用上面的访问代码来访问配置结构,我们需要生成一个特定的配置读取类(ConfigurationSectionHandler),例子很简单,就不多做说明了:
22public class MyInfoSectionHandler: IConfigurationSectionHandler
23{
24public object Create(object parent, object configContext, System.Xml.XmlNode section)
25{
26Hashtable config = new Hashtable();
27foreach(XmlNode node in section.ChildNodes)
28{
29if(node.Name != "myInfo")
30throw new System.Configuration.ConfigurationException("不可识别的配置项", node);
31
32Hashtable item = new Hashtable();
33foreach(XmlAttribute attr in node.Attributes)
34{
35switch(attr.Name)
36{
37case "Area":
38case "Device":
39case "Customer":
40item.Add(attr.Name, attr.Value);
41break;
42default:
43throw new System.Configuration.ConfigurationException("不可识别的配置属性", attr);
44}
45}
46config.Add(item["Area"], item);
47}
48return config;
49}
50}
51
52然后,我们再定义配置说明。其中,myNamespace.MyInfoSectionHandler 是MyInfoSectionHandler类的带名字空间的完整名称;myApp 则是定义MyInfoSectionHandler类的程序集不带扩展名的名字(如myApp.dll或myApp.exe):
53<?xml version="1.0" encoding="utf-8"?>
54<configuration>
55<!-- 以下是自定义配置的声明 -->
56<configsections>
57<section name="myConfig" type="myNamespace.MyInfoSectionHandler, myApp"></section>
58</configsections>
59<myconfigs>
60<myinfo area="Fuzhou" customer="Muf" device="Printer"></myinfo>
61<myinfo area="Shanghai" customer="Liny" device="Mobile"></myinfo>
62
63</myconfigs></configuration>
64
65根据上面的例子,我们可以使用IConfigurationSectionHandler来实现任意的配置文件结构。
66
67(待续)</myconfigs>