您的位置:首页 > 其它

【转】如何使用.NET配置文件(一)

2010-06-21 13:50 736 查看

  
 
  
  

        相应访问代码如下:       

string fileName = System.Configuration.ConfigurationSettings.AppSettings.Get("LogFile");
     2. 自定义配置节(section)名称
        比如,我们要使用下面的配置结构,将配置信息归类分组:





  
    
     
    
  

  
    
     
    
  

      Area="Fuzhou" Device="Printer" Customer="Muf"
  />


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

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


    把上面的声明段放入配置文件中,我们的配置结构就可以正常使用了。声明中,< sectionGroup>用来定义不含配置数据的节的名称。用来定义含有自定义配置数据的节的名称。< section type>用来指定定义配置数据的类型。

    注意,自定义的配置节,不能使用 System.Configuration.ConfigurationSettings.AppSettings.Get 来访问,要使用 System.Configuration.ConfigurationSettings.GetConfig。

    .NET已经定义了3种配置类型:
  a. NameValueSectionHandler
        相应访问代码如下: 

NameValueCollection myNameValue= (NameValueCollection)System.Configuration.ConfigurationSettings.GetConfig(@"myConfig/myNameValue");
string Area = myNameValue["Area"];
string Device= myNameValue["Device"];
string Customer = myNameValue["Customer "];
  b. DictionarySectionHandler
        相应访问代码如下:

Hashtable myNameValue= (Hashtable)System.Configuration.ConfigurationSettings.GetConfig(@"myConfig/myDictionary");
string Area = myNameValue["Area"];
string Device= myNameValue["Device"];
string Customer = myNameValue["Customer "];
  c. SingleTagSectionHandler
        相应访问代码如下:   

Hashtable myNameValue= (Hashtable)System.Configuration.ConfigurationSettings.GetConfig(@"myConfig/myInfo");
string Area = myNameValue["Area"];
string Device= myNameValue["Device"];
string Customer = myNameValue["Customer "];
        这三种类型的详细信息,可以参考 MSDN 文档。同时.NET 还定义了IgnoreSectionHandler类型,为 System.Configuration 之外的系统所读取和处理的配置节提供节处理程序定义。
        除此之外,.NET提供了IConfigurationSectionHandler接口,这样我们还可以自行进行扩展,以设计出我们自已的配置形式。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: