今天在使用Nlog的時(shí)候,發(fā)現(xiàn)了一個(gè)之前沒(méi)注意的問(wèn)題。

以前,我的app配置文件都是這么寫的,當(dāng)然配置比較多的時(shí)候會(huì)改用xml。

如果<appSettings>節(jié)點(diǎn)中的內(nèi)容很多的話,我自己有時(shí)候都分不清哪個(gè)是做什么的,可能朋友們會(huì)說(shuō),你加個(gè)注釋不就行了。但是可不可以把一些相同的配置放在一起呢,就像上面的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元素開始到網(wǎng)上風(fēng)暴了一番。ConfigurationSection 類
然后知道可以通過(guò)ConfigurationManager類的GetSection方法獲取到配置文件的信息。(如果應(yīng)用程序需要以只讀方式訪問(wèn)其自身配置,則對(duì)于 Web 應(yīng)用程序,建議使用 GetSection() 重載方法;對(duì)于客戶端應(yīng)用程序,建議使用 ConfigurationManager.GetSection 方法。----MSDN)
var mySection = ConfigurationManager.GetSection("mySection");運(yùn)行一下程序試試,迎來(lái)了第一個(gè)異常。System.Configuration.ConfigurationErrorsException:創(chuàng)建mySection的配置節(jié)處理程序時(shí)出錯(cuò):類型“ConfigSolution.ConfigSectionHandler”不從“System.Configuration.IConfigurationSectionHandler”繼承。--->System.TypeLoadException:類型“ConfigSolution.ConfigSectionHandler”不從“System.Configuration.IConfigurationSectionHandler”繼承。
既然說(shuō)我的ConfigSolution.ConfigSectionHandler不從System.Configuration.IConfigurationSectionHandler繼承,那好,我就繼承它,然后看看這個(gè)接口都有些什么東西,Ctrl+T一下(SharpDevelop的快捷鍵),這接口就一個(gè)方法
直接MSDN一下,IConfigurationSectionHandler.Create 信息量不是很大,就一句話:IConfigurationSectionHandler.Create方法,創(chuàng)建配置節(jié)處理程序。算了,直接斷點(diǎn)跟蹤一下,果然有東西

好了,剩下的就是對(duì)xml的讀取了。直接把section return看看,

這回程序正常運(yùn)行了,且mySection也拿到了配置文件

但是在程序中我們?cè)趺传@取這些配置數(shù)據(jù)呢?我創(chuàng)建了一個(gè)處理配置文件的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>
運(yùn)行結(jié)果:

好了,一切完成。
MSDN:https://msdn.microsoft.com/zh-cn/sqlserver/ms228056(v=vs.71).aspx
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注