在web.config和app.config文件中增加自定義配置節點

有經驗的開發人員都知道在開發.NET應用時可以利用配置文件保存一些常用並且有可能變化的信息,例如日誌文件的保存路徑、數據庫連接信息等等,這樣即使生產環境中的參數信息與開發環境不一致也只需要更改配置文件而不用改動源代碼再重新編譯,極其方便。並且我們一般還約定,在<appSettings>節點保存應用程序的配置信息,在<connectionStrings>中保存數據庫連接字符串信息(詳見本博客《asp.net夜話之十一:web.config詳解》)。
上面的這些方法和約定足以讓我們在大部分開發中獲得方便,但是在有些情況下有些配置信息可以按組分類存放,如果採用上面的方法不僅不直觀,而且讀取起來也不是太方便,幸好在.NET裏就提供了這樣的方法。如果有使用過Log4Net或者Enyim.Caching的朋友,肯定對下面的配置不會陌生:

[xhtml] view plaincopy
  1. <sectionGroup name="enyim.com"><section name="memcached" type="Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching" /></sectionGroup>  

或:

[xhtml] view plaincopy
  1. <configSections><section name="log4net" type="System.Configuration.IgnoreSectionHandler"/></configSections>  

在出現上面配置的配置文件中,我們就會找到名稱爲"enyim.com"或者"log4net"的節點,儘管它們本不屬於config文件的默認節點,但是通過上面的配置之後程序運行並不會報錯。這樣一來,相關配置信息也可以很好分類保存起來。
在這裏周公演示一個簡單的例子,這個例子來源於周公的一個從2006年起就開始開發的自用軟件(因爲沒有美化所以沒有免費發佈),在這個應用程序的connfig文件中我增加了一些特有的配置,所以新增了一個自己的節點,app.config文件內容如下:

[xhtml] view plaincopy
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <configuration>  
  3.   <configSections>  
  4.       <section name="SoftwareSettings" type="ImageAssistant.Configuration.SoftwareSettings, ImageAssistant" />  
  5.   </configSections>  
  6.   <SoftwareSettings>  
  7.     <LoadSettings>  
  8.       <add key="LoadBmp" value="true"/>  
  9.       <add key="LoadJpg" value="true"/>  
  10.       <add key="LoadGif" value="true"/>  
  11.       <add key="LoadPng" value="false"/>  
  12.     </LoadSettings>  
  13.     <PathSettings SavePath="C:/ResizeImages/" SearchSubPath="true"/>  
  14.   </SoftwareSettings>  
  15.   <appSettings>  
  16.     <add key="LoadBmp" value="true"/>  
  17.     <add key="LoadJpg" value="true"/>  
  18.     <add key="LoadGif" value="true"/>  
  19.     <add key="LoadPng" value="false"/>  
  20.     <add key="IncludeSubPath"  value="true"/>  
  21.   </appSettings>  
  22.     
  23. </configuration>  

在config文件中我們使用<section name="SoftwareSettings" type="ImageAssistant.Configuration.SoftwareSettings, ImageAssistant" />告訴應用程序對於配置文件中的SoftwareSettings節點,其對應的類是ImageAssistant程序集中ImageAssistant.Configuration.SoftwareSettings類,並且在<SoftwareSettings>節點中我們還看到有<LoadSettings>節點和<PathSettings>節點,其中<LoadSettings>是一個節點集合,還包含有多個子節點,爲了表示清楚這些關係我們需要添加四個類:SoftwareSettings、LoadSettingsCollection、LoadSettingsElement及PathSettingElement。爲了發佈方便,周公將這四個類的代碼放在一個物理文件中,代碼如下(注意添加對System.Configuration.dll的引用):

[c-sharp] view plaincopy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Configuration;  
  6.   
  7. //作者:zhoufoxcn(周公)  
  8. //日期:2011-03-08  
  9. //blog:http://blog.csdn.net/zhoufoxcn 或http://zhoufoxcn.blog.51cto.com  
  10. //版權聲明:本文允許非商業用途,但必須保證不得去掉本文中的任何鏈接,違者必究。  
  11. namespace ImageAssistant.Configuration  
  12. {  
  13.     public sealed class LoadSettingsCollection : ConfigurationElementCollection  
  14.     {  
  15.         private IDictionary<stringbool> settings;  
  16.   
  17.         protected override ConfigurationElement CreateNewElement()  
  18.         {  
  19.             return new LoadSettingsElement();  
  20.         }  
  21.   
  22.         protected override object GetElementKey(ConfigurationElement element)  
  23.         {  
  24.             LoadSettingsElement ep = (LoadSettingsElement)element;  
  25.   
  26.             return ep.Key;  
  27.         }  
  28.   
  29.         protected override string ElementName  
  30.         {  
  31.             get  
  32.             {  
  33.                 return base.ElementName;  
  34.             }  
  35.         }  
  36.   
  37.         public IDictionary<stringbool> Settings  
  38.         {  
  39.             get  
  40.             {  
  41.                 if (settings == null)  
  42.                 {  
  43.                     settings = new Dictionary<stringbool>();  
  44.                     foreach (LoadSettingsElement e in this)  
  45.                     {  
  46.                         settings.Add(e.Key, e.Value);  
  47.                     }  
  48.                 }  
  49.                 return settings;  
  50.             }  
  51.         }  
  52.   
  53.         public bool this[string key]  
  54.         {  
  55.             get  
  56.             {  
  57.                 bool isLoad = true;  
  58.                 if (settings.TryGetValue(key, out isLoad))  
  59.                 {  
  60.                     return isLoad;  
  61.                 }  
  62.                 else  
  63.                 {  
  64.                     throw new ArgumentException("沒有對'" + key + "'節點進行配置。");  
  65.                 }  
  66.             }  
  67.         }  
  68.   
  69.     }  
  70.   
  71.     public class LoadSettingsElement : ConfigurationElement  
  72.     {  
  73.         [ConfigurationProperty("key", IsRequired = true)]  
  74.         public string Key  
  75.         {  
  76.             get { return (string)base["key"]; }  
  77.             set { base["key"] = value; }  
  78.         }  
  79.         [ConfigurationProperty("value", IsRequired = true)]  
  80.         public bool Value  
  81.         {  
  82.             get { return (bool)base["value"]; }  
  83.             set { base["value"] = value; }  
  84.         }  
  85.     }  
  86.   
  87.     public class PathSettingElement : ConfigurationElement  
  88.     {  
  89.         /// <summary>  
  90.         ///   
  91.         /// </summary>  
  92.         [ConfigurationProperty("SavePath", IsRequired = true)]  
  93.         public string SavePath  
  94.         {  
  95.             get { return (string)base["SavePath"]; }  
  96.             set { base["SavePath"] = value; }  
  97.         }  
  98.         /// <summary>  
  99.         ///   
  100.         /// </summary>  
  101.         [ConfigurationProperty("SearchSubPath", IsRequired = false, DefaultValue = true)]  
  102.         public bool SearchSubPath  
  103.         {  
  104.             get { return (bool)base["SearchSubPath"]; }  
  105.             set { base["SearchSubPath"] = value; }  
  106.         }  
  107.     }  
  108.   
  109.     /// <summary>  
  110.     /// 對應config文件中的  
  111.     /// </summary>  
  112.     public sealed class SoftwareSettings : ConfigurationSection  
  113.     {  
  114.         /// <summary>  
  115.         /// 對應SoftwareSettings節點下的LoadSettings子節點  
  116.         /// </summary>  
  117.         [ConfigurationProperty("LoadSettings", IsRequired = true)]  
  118.         public LoadSettingsCollection LoadSettings  
  119.         {  
  120.             get { return (LoadSettingsCollection)base["LoadSettings"]; }  
  121.         }  
  122.   
  123.         /// <summary>  
  124.         /// 對應SoftwareSettings節點下的PathSettings子節點,非必須  
  125.         /// </summary>  
  126.         [ConfigurationProperty("PathSettings", IsRequired = false)]  
  127.         public PathSettingElement PathSetting  
  128.         {  
  129.             get { return (PathSettingElement)base["PathSettings"]; }  
  130.             set { base["PathSettings"] = value; }  
  131.         }  
  132.   
  133.     }  
  134. }  

在上面的代碼中可以看到ConfigurationProperty這個屬性,這是表示對應的屬性在config文件中的屬性名,IsRequired表示是否是必須的屬性,還有DefaultValue表示屬性的默認值。初次之外,我們還要注意以下關係:
SoftwareSettings:根節點,繼承自ConfigurationSection。
LoadSettingsCollection:子節點集合,繼承自ConfigurationElementCollection。
LoadSettingsElement:子節點,繼承自ConfigurationElement。
PathSettingElement:子節點,繼承自ConfigurationElement。
編寫了如下代碼之後,我們又該如何使用上面的類呢?其實很簡單,如下:

[c-sharp] view plaincopy
  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             SoftwareSettings softSettings = ConfigurationManager.GetSection("SoftwareSettings"as SoftwareSettings;  
  6.   
  7.             foreach (string key in softSettings.LoadSettings.Settings.Keys)  
  8.             {  
  9.                 Console.WriteLine("{0}={1}", key, softSettings.LoadSettings[key]);  
  10.             }  
  11.             Console.WriteLine("SavePath={0},SearchSubPath={1}", softSettings.PathSetting.SavePath, softSettings.PathSetting.SearchSubPath);  
  12.             Console.ReadLine();  
  13.         }  
  14.     }  

這個程序的運行結果如下:
LoadBmp=True
LoadJpg=True
LoadGif=True
LoadPng=False
SavePath=C:/ResizeImages/,SearchSubPath=True

總結:在上面的config文件中通過<appSettings>也達到了類似的效果,但是通過自定義節點我們可以方便地讀取相關的應用程序配置,同時也便於維護。如果在開發過程中遇到本文中類似的情況,不妨採取本文所述的方式。本文示例源代碼可以到這裏下載。

周公
2011-03-08

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章