用来指定定义配置数据的类型。.NET已经定义了3种配置类型:
a. NameValueSectionHandler 相应访问代码如下:
NameValueCollectionmyNameValue=(NameValueCollection)System.Configuration.ConfigurationSettings.AppSettings.Get(@"myConfig\myNameValue");
stringArea=myNameValue["Area"];
stringDevice=myNameValue["Device"];
stringCustomer=myNameValue["Customer"];
b. DictionarySectionHandler
相应访问代码如下:
HashtablemyNameValue=(Hashtable)System.Configuration.ConfigurationSettings.AppSettings.Get(@"myConfig\myDictionary");
stringArea=myNameValue["Area"];
stringDevice=myNameValue["Device"];
stringCustomer=myNameValue["Customer"];
c. SingleTagSectionHandler
相应访问代码如下:
HashtablemyNameValue=(Hashtable)System.Configuration.ConfigurationSettings.AppSettings.Get(@"myConfig\myInfo");
stringArea=myNameValue["Area"];
stringDevice=myNameValue["Device"];
stringCustomer=myNameValue["Customer"];
这三种类型的详细信息,可以参考 MSDN 文档。同时.NET 还定义了IgnoreSectionHandler类型,为 System.Configuration 之外的系统所读取和处理的配置节提供节处理程序定义。
除此之外,.NET提供了IConfigurationSectionHandler接口,这样我们还可以自行进行扩展,以设计出我们自已的配置形式。
3. 自定义配置结构 (使用IConfigurationSectionHandler)
假设有以下的配置信息,其在MyInfo可以重复许多次,那么应如何读取配置呢?这时就要使用自定义的配置程序了。
<myConfigs>
<myInfoArea="Fuzhou"Device="Printer"Customer="Muf"/>
<myInfoArea="Shanghai"Device="Mobile"Customer="Liny"/>
< SPAN>myConfig>
访问代码如下:
HashtablecfgTable=(Hashtable)ConfigurationSettings.GetConfig("myConfigs");
Debug.Assert(cfgTable.Count==2);
HashtablecfgFuzhou=(Hashtable)cfgTable["Fuzhou"];
HashtablecfgShanghai=(Hashtable)cfgTable["Shanghai"];
Debug.Assert(cfgFuzhou["Device"]=="Printer");
Debug.Assert(cfgShanghai["Device"]=="Mobile");
Debug.Assert(cfgFuzhou["Customer"]=="Muf");
Debug.Assert(cfgShanghai["Customer"]=="Liny");
foreach(HashtablecfgincfgTable.Values)
{
Console.WriteLine("Area={0}Device={1}Customer={2}",cfg["Area"],cfg["Device"],cfg["Customer"]);
}
为了能使用上面的访问代码来访问配置结构,我们需要生成一个特定的配置读取类(ConfigurationSectionHandler),例子很简单,就不多做说明了:
publicclassMyInfoSectionHandler:IConfigurationSectionHandler
{
publicobjectCreate(objectparent,objectconfigContext,System.Xml.XmlNodesection)
{
Hashtableconfig=newHashtable();
foreach(XmlNodenodeinsection.ChildNodes)
{
if(node.Name!="myInfo")
thrownewSystem.Configuration.ConfigurationException("不可识别的配置项",node);
Hashtableitem=newHashtable();
foreach(XmlAttributeattrinnode.Attributes)
{
switch(attr.Name)
{
case"Area":
case"Device":
case"Customer":
item.Add(attr.Name,attr.Value);
break;
default:
thrownewSystem.Configuration.ConfigurationException("不可识别的配置属性",attr);
}
}
config.Add(item["Area"],item);
}
returnconfig;
}
}
然后,我们再定义配置说明。其中,myNamespace.MyInfoSectionHandler 是MyInfoSectionHandler类的带名字空间的完整名称;myApp 则是定义MyInfoSectionHandler类的程序集不带扩展名的名字(如myApp.dll或myApp.exe):
<configuration>
<configSections>
<sectionname="myConfig"type="myNamespace.MyInfoSectionHandler,myApp"/>
< SPAN>configSections>
<myConfigs>
<myInfoArea="Fuzhou"Device="Printer"Customer="Muf"/>
<myInfoArea="Shanghai"Device="Mobile"Customer="Liny"/>
< SPAN>myConfig>
< SPAN>configuration>
根据上面的例子,我们可以使用IConfigurationSectionHandler来实现任意的配置文件结构。