当前位置: 移动技术网 > IT编程>开发语言>c# > 详解C#读取Appconfig中自定义的节点

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

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

运行结果:

好了,一切完成。

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网