首页 > 学院 > 开发设计 > 正文

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

2019-11-17 02:23:22
字体:
来源:转载
供稿:网友

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

  今天在使用Nlog的时候,发现了一个之前没注意的问题。

  以前,我的app配置文件都是这么写的,当然配置比较多的时候会改用xml

如果<appSettings>节点中的内容很多的话,我自己有时候都分不清哪个是做什么的,可能朋友们会说,你加个注释不就行了。但是可不可以把一些相同的配置放在一起呢,就像上面的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元素开始到网上风暴了一番。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类,大体如下

 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>

运行结果:

好了,一切完成。

MSDN:https://msdn.microsoft.com/zh-cn/sqlserver/ms228056(v=vs.71).aspx


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表