国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

詳解C#讀取Appconfig中自定義的節點

2020-01-24 01:42:46
字體:
來源:轉載
供稿:網友

今天在使用Nlog的時候,發現了一個之前沒注意的問題。

  以前,我的app配置文件都是這么寫的,當然配置比較多的時候會改用xml。

 如果<appSettings>節點中的內容很多的話,我自己有時候都分不清哪個是做什么的,可能朋友們會說,你加個注釋不就行了。但是可不可以把一些相同的配置放在一起呢,就像上面的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 元素開始到網上風暴了一番。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類,大體如下

   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>

運行結果:

好了,一切完成。

以上所述就是本文的全部內容了,希望大家能夠喜歡。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 明溪县| 南澳县| 纳雍县| 修文县| 申扎县| 甘洛县| 兰州市| 章丘市| 左贡县| 陕西省| 江津市| 潼南县| 益阳市| 夹江县| 涡阳县| 永泰县| 本溪市| 汽车| 钟山县| 太和县| 梨树县| 西吉县| 嘉兴市| 柳江县| 丰宁| 丽水市| 体育| 福州市| 开封市| 江口县| 兴安盟| 灵丘县| 高淳县| 锡林郭勒盟| 图们市| 普兰县| 五大连池市| 洛川县| 民乐县| 麻城市| 泗阳县|