詳解C#讀取Appconfig中自定義的節(jié)點
今天在使用Nlog的時候,發(fā)現(xiàn)了一個之前沒注意的問題。
以前,我的app配置文件都是這么寫的,當然配置比較多的時候會改用xml。
如果<appSettings>節(jié)點中的內(nèi)容很多的話,我自己有時候都分不清哪個是做什么的,可能朋友們會說,你加個注釋不就行了。但是可不可以把一些相同的配置放在一起呢,就像上面的nlog一樣。先試著改造下配置文件
<configSections>
<section name="mySection" type="ConfigSolution.ConfigSectionHandler,ConfigSolution"></section>
</configSections>
<mySection>
<port CPort="40001" WPort="40002" SPort="50000"></port>
<coustomAssembly CommandsAssembly="HX.Components.Command.Collection" CommandMessagesAssembly="HX.Components.CommandMessage.Collection"></coustomAssembly>
</mySection>
那么,怎么獲取section里的值呢?從configSections 元素開始到網(wǎng)上風暴了一番。ConfigurationSection 類
然后知道可以通過ConfigurationManager類的GetSection方法獲取到配置文件的信息。(如果應(yīng)用程序需要以只讀方式訪問其自身配置,則對于 Web 應(yīng)用程序,建議使用 GetSection() 重載方法;對于客戶端應(yīng)用程序,建議使用 ConfigurationManager.GetSection 方法。----MSDN)
var mySection = ConfigurationManager.GetSection("mySection");
運行一下程序試試,迎來了第一個異常。System.Configuration.ConfigurationErrorsException: 創(chuàng)建 mySection 的配置節(jié)處理程序時出錯: 類型“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 方法,創(chuàng)建配置節(jié)處理程序。算了,直接斷點跟蹤一下,果然有東西
好了,剩下的就是對xml的讀取了。直接把section return看看,
這回程序正常運行了,且mySection 也拿到了配置文件
但是在程序中我們怎么獲取這些配置數(shù)據(jù)呢?我創(chuàng)建了一個處理配置文件的MySectionHelper類,大體如下
public class MySectionHelper { readonly XmlNode _section; readonly XmlNode _coustomAssembly; public MySectionHelper(XmlNode section) { _section=section; _coustomAssembly= _section.SelectSingleNode("coustomAssembly"); } public string CommandsAssembly{get{return _coustomAssembly.Attributes["CommandsAssembly"].Value;}} }
試試行不行,我的配置文件
<configSections> <section name="mySection" type="ConfigSolution.ConfigSectionHandler,ConfigSolution"></section> </configSections> <mySection> <port CPort="40001" WPort="40002" SPort="50000"></port> <coustomAssembly CommandsAssembly="HX.Components.Command.Collection" CommandMessagesAssembly="HX.Components.CommandMessage.Collection"></coustomAssembly> </mySection>
運行結(jié)果:
好了,一切完成。
以上所述就是本文的全部內(nèi)容了,希望大家能夠喜歡。
相關(guān)文章
C#學(xué)習(xí)基礎(chǔ)概念二十五問續(xù)2
C#學(xué)習(xí)基礎(chǔ)概念二十五問續(xù)2...2007-04-04C#將圖片和字節(jié)流互相轉(zhuǎn)換并顯示到頁面上
本文主要介紹用C#實現(xiàn)圖片轉(zhuǎn)換成字節(jié)流,字節(jié)流轉(zhuǎn)換成圖片,并根據(jù)圖片路徑返回圖片的字節(jié)流,有需要的朋友可以參考下2015-08-08C#以太網(wǎng)Sockets客戶端設(shè)計實現(xiàn)
本文主要介紹了C#以太網(wǎng)Sockets客戶端設(shè)計實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02