如何使用.NET配置文件(转载)

本文介绍如何在.NET应用程序中扩展配置文件的功能,包括自定义配置节、配置结构及使用IConfigurationSectionHandler实现复杂配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  .NET的应用程序配置文件,使用的是XML格式。相对INI文件来说,它的功能要强上不少,而且具有很强的可扩展性。它的缺点是不能直接进行写操作,也就是说,不能直接在程序中修改配置文件的数据(当然不是指不能,不过不是本文讨论的范围)。本文主要目的是探讨如何扩展配置文件,并在其加入各种自定义配置信息。
   
    1. 使用
        简单的配置信息,可以直接放入标记中。如:
None.gifxml version="1.0" encoding="utf-8"?>
None.gif  
<appSettings>
None.gif 
<add key="LogFile" value="d:\log\debug.log"/>
None.gif  
< SPAN>appSettings>  
None.gif
< SPAN>configuration>
None.gif

        相应访问代码如下:       

None.gifstring fileName = System.Configuration.ConfigurationSettings.AppSettings.Get("LogFile");
None.gif

     2. 自定义配置节(section)名称
        比如,我们要使用下面的配置结构,将配置信息归类分组:

None.gifxml version="1.0" encoding="utf-8"?>
None.gif
<configuration>
None.gif

None.gif

None.gif
<myConfig>
None.gif  
<myDictionary>
None.gif    
<add key="Area" value="Fuzhou"/>
None.gif    
<add key="Device" value="Printer"/> 
None.gif    
<add key="Customer" value="Muf"/>
None.gif  
< SPAN>myDictionary>
None.gif  
<myNameValue>
None.gif    
<add key="Area" value="Fuzhou"/>
None.gif    
<add key="Device" value="Printer"/> 
None.gif    
<add key="Customer" value="Muf"/>
None.gif  
< SPAN>myNameValue>
None.gif  
<myInfo
None.gif    
Area="Fuzhou" Device="Printer" Customer="Muf"
None.gif  
/>
None.gif
< SPAN>myConfig>
None.gif
< SPAN>configuration>
None.gif

        但是光这样子说明是不行的。没有声明,是不能使用自定义的配置段。我们必须要在配置文件前面加入声明:  

None.gif
None.gif  
<configSections>
None.gif    
<sectionGroup name="myConfig">
None.gif         
<section name="myDictionary"
None.gif            type
="System.Configuration.NameValueSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
None.gif        
<section name="myNameValue"
None.gif            type
="System.Configuration.DictionarySectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
None.gif        
<section name="myInfo"
None.gif            type
="System.Configuration.SingleTagSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
None.gif    
< SPAN>sectionGroup>
None.gif  
< SPAN>configSections>  
None.gif

    声明和配置的关系,示意图如下:
        
    由图上可以看出,NameValueSectionHandler和DictionarySectionHandler在定义配置文件的内容形式上是一样的,都是用来设置内容的。只是返回到C#中的类不太一样,可以参考下面的代码示例。
    另外,如果不关心Handler类的版本等信息,可以直接省略。如NameValueSectionHandler可以直接如下声明:

None.gif<section name="myDictionary"            type="System.Configuration.NameValueSectionHandler, System" />
None.gif

    把上面的声明段放入配置文件中,我们的配置结构就可以正常使用了。声明中,用来定义不含配置数据的节的名称。用来定义含有自定义配置数据的节的名称。用来指定定义配置数据的类型。.NET已经定义了3种配置类型:
  a. NameValueSectionHandler
        相应访问代码如下: 

None.gifNameValueCollection myNameValue= (NameValueCollection)System.Configuration.ConfigurationSettings.AppSettings.Get(@"myConfig\myNameValue");
None.gif
string Area = myNameValue["Area"];
None.gif
string Device= myNameValue["Device"];
None.gif
string Customer = myNameValue["Customer "];
None.gif

  b. DictionarySectionHandler
        相应访问代码如下:

None.gifHashtable myNameValue= (Hashtable)System.Configuration.ConfigurationSettings.AppSettings.Get(@"myConfig\myDictionary");
None.gif
string Area = myNameValue["Area"];
None.gif
string Device= myNameValue["Device"];
None.gif
string Customer = myNameValue["Customer "];
None.gif

  c. SingleTagSectionHandler
        相应访问代码如下:   

None.gifHashtable myNameValue= (Hashtable)System.Configuration.ConfigurationSettings.AppSettings.Get(@"myConfig\myInfo");
None.gif
string Area = myNameValue["Area"];
None.gif
string Device= myNameValue["Device"];
None.gif
string Customer = myNameValue["Customer "];
None.gif

        这三种类型的详细信息,可以参考 MSDN 文档。同时.NET 还定义了IgnoreSectionHandler类型,为 System.Configuration 之外的系统所读取和处理的配置节提供节处理程序定义。
        除此之外,.NET提供了IConfigurationSectionHandler接口,这样我们还可以自行进行扩展,以设计出我们自已的配置形式。

        3. 自定义配置结构 (使用IConfigurationSectionHandler)
 假设有以下的配置信息,其在MyInfo可以重复许多次,那么应如何读取配置呢?这时就要使用自定义的配置程序了。
None.gif<myConfigs>
None.gif  
<myInfo Area="Fuzhou" Device="Printer" Customer="Muf" />
None.gif  
<myInfo Area="Shanghai" Device="Mobile" Customer="Liny" />
None.gif
< SPAN>myConfig>
None.gif

 访问代码如下:

None.gifHashtable cfgTable = (Hashtable)ConfigurationSettings.GetConfig( "myConfigs" );
None.gif
None.gifDebug.Assert( cfgTable.Count 
== 2);
None.gifHashtable cfgFuzhou 
= (Hashtable)cfgTable["Fuzhou"];
None.gifHashtable cfgShanghai 
= (Hashtable)cfgTable["Shanghai"];
None.gifDebug.Assert( cfgFuzhou[
"Device"== "Printer" );
None.gifDebug.Assert( cfgShanghai[
"Device"== "Mobile" );
None.gifDebug.Assert( cfgFuzhou[
"Customer"== "Muf" );
None.gifDebug.Assert( cfgShanghai[
"Customer"== "Liny" );
None.gif
None.gif
foreach(Hashtable cfg in cfgTable.Values)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif Console.WriteLine(
"Area={0} Device={1} Customer={2}", cfg["Area"], cfg["Device"], cfg["Customer"]);
ExpandedBlockEnd.gif}

None.gif
None.gif

 为了能使用上面的访问代码来访问配置结构,我们需要生成一个特定的配置读取类(ConfigurationSectionHandler),例子很简单,就不多做说明了:

None.gifpublic class MyInfoSectionHandler: IConfigurationSectionHandler
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif 
public object Create(object parent, object configContext, System.Xml.XmlNode section)
ExpandedSubBlockStart.gifContractedSubBlock.gif 
dot.gif{
InBlock.gif  Hashtable config 
= new Hashtable();
InBlock.gif  
foreach(XmlNode node in section.ChildNodes)
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   
if(node.Name != "myInfo")
InBlock.gif    
throw new System.Configuration.ConfigurationException("不可识别的配置项", node);
InBlock.gif
InBlock.gif   Hashtable item 
= new Hashtable();
InBlock.gif   
foreach(XmlAttribute attr in node.Attributes)
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{
InBlock.gif    
switch(attr.Name)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif     
case "Area":
InBlock.gif     
case "Device":
InBlock.gif     
case "Customer":
InBlock.gif      item.Add(attr.Name, attr.Value);
InBlock.gif      
break;
InBlock.gif     
default:
InBlock.gif      
throw new System.Configuration.ConfigurationException("不可识别的配置属性", attr);
ExpandedSubBlockEnd.gif    }

ExpandedSubBlockEnd.gif   }

InBlock.gif   config.Add(item[
"Area"], item);
ExpandedSubBlockEnd.gif  }

InBlock.gif  
return config;
ExpandedSubBlockEnd.gif }

ExpandedBlockEnd.gif}

None.gif
None.gif

 然后,我们再定义配置说明。其中,myNamespace.MyInfoSectionHandler 是MyInfoSectionHandler类的带名字空间的完整名称;myApp 则是定义MyInfoSectionHandler类的程序集不带扩展名的名字(如myApp.dll或myApp.exe):

None.gifxml version="1.0" encoding="utf-8"?>
None.gif
<configuration>
None.gif  

None.gif  
<configSections>
None.gif      
<section name="myConfig" type="myNamespace.MyInfoSectionHandler, myApp" />
None.gif  
< SPAN>configSections>   
None.gif  
<myConfigs>
None.gif    
<myInfo Area="Fuzhou" Device="Printer" Customer="Muf" />
None.gif    
<myInfo Area="Shanghai" Device="Mobile" Customer="Liny" />
None.gif  
< SPAN>myConfig>
None.gif
< SPAN>configuration>
None.gif

 根据上面的例子,我们可以使用IConfigurationSectionHandler来实现任意的配置文件结构。

转载于:https://www.cnblogs.com/BoKeRen/archive/2007/04/16/715233.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值