今天在使用Nlog的時候,發現了一個之前沒注意的問題。
以前,我的app配置檔案都是這麼寫的,當然配置比較多的時候會改用xml。
如果<appSettings>節點中的内容很多的話,我自己有時候都分不清哪個是做什麼的,可能朋友們會說,你加個注釋不就行了。但是可不可以把一些相同的配置放在一起呢,就像上面的nlog一樣。先試着改造下配置檔案
1 <configSections>
2 <section name="mySection" type="ConfigSolution.ConfigSectionHandler,ConfigSolution"></section>
3 </configSections>
4 <mySection>
5 <port CPort="40001" WPort="40002" SPort="50000"></port>
6 <coustomAssembly CommandsAssembly="HX.Components.Command.Collection" CommandMessagesAssembly="HX.Components.CommandMessage.Collection"></coustomAssembly>
7 </mySection>
那麼,怎麼擷取section裡的值呢?從configSections 元素開始到網上風暴了一番。ConfigurationSection 類
然後知道可以通過ConfigurationManager類的GetSection方法擷取到配置檔案的資訊。(如果應用程式需要以隻讀方式通路其自身配置,則對于 Web 應用程式,建議使用 GetSection() 重載方法;對于用戶端應用程式,建議使用 ConfigurationManager.GetSection 方法。----MSDN)
var mySection = ConfigurationManager.GetSection("mySection");
運作一下程式試試,迎來了第一個異常。System.Configuration.ConfigurationErrorsException: 建立 mySection 的配置節處理程式時出錯: 類型“ConfigSolution.ConfigSectionHandler”不從“System.Configuration.IConfigurationSectionHandler”繼承。 ---> System.TypeLoadException: 類型“ConfigSolution.ConfigSectionHandler”不從“System.Configuration.IConfigurationSectionHandler”繼承。
既然說我的ConfigSolution.ConfigSectionHandler不從System.Configuration.IConfigurationSectionHandler繼承,那好,我就繼承它,然後看看這個接口都有些什麼東西,Ctrl+T一下(SharpDevelop的快捷鍵),這接口就一個方法
直接MSDN一下,IConfigurationSectionHandler.Create 資訊量不是很大,就一句話:IConfigurationSectionHandler.Create 方法,建立配置節處理程式。算了,直接斷點跟蹤一下,果然有東西
好了,剩下的就是對xml的讀取了。直接把section return看看,
這回程式正常運作了,且mySection 也拿到了配置檔案

但是在程式中我們怎麼擷取這些配置資料呢?我建立了一個處理配置檔案的MySectionHelper類,大體如下
1 public class MySectionHelper
2 {
3 readonly XmlNode _section;
4 readonly XmlNode _coustomAssembly;
5 public MySectionHelper(XmlNode section)
6 {
7 _section=section;
8 _coustomAssembly= _section.SelectSingleNode("coustomAssembly");
9 }
10
11 public string CommandsAssembly{get{return _coustomAssembly.Attributes["CommandsAssembly"].Value;}}
12 }
試試行不行,我的配置檔案
1 <configSections>
2 <section name="mySection" type="ConfigSolution.ConfigSectionHandler,ConfigSolution"></section>
3 </configSections>
4 <mySection>
5 <port CPort="40001" WPort="40002" SPort="50000"></port>
6 <coustomAssembly CommandsAssembly="HX.Components.Command.Collection" CommandMessagesAssembly="HX.Components.CommandMessage.Collection"></coustomAssembly>
7 </mySection>
運作結果:
好了,一切完成。
https://msdn.microsoft.com/zh-cn/sqlserver/ms228056(v=vs.71).aspx