详解C#读取Appconfig中自定义的节点

今天在使用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>

运行结果:

好了,一切完成。

以上所述就是本文的全部内容了,希望大家能够喜欢。