c#-在运行时修改app.config部分
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c#-在运行时修改app.config部分,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2286字,纯文字阅读大概需要4分钟。
内容图文
![c#-在运行时修改app.config部分](/upload/InfoBanner/zyjiaocheng/683/cedb6b37d8b841669daee0af33f6b336.jpg)
我需要修改< configuration>< system.diagnostics>运行时的app.config部分,以便我可以:
>在< sharedListeners>下添加CustomTraceListener.元素,它需要特殊的initializeData,只能在运行时确定.
>将CustomTraceListener共享的侦听器添加到< source>< listeners>下的现有源.元件.
>将CustomTraceListener持久保存到其他程序集,这些程序集将从配置文件中加载其跟踪源和侦听器配置.
app.config中的相关部分目前看起来像这样:
<system.diagnostics>
<sources>
<source name="mysource" switchName="..." switchType="...">
<listeners>
<add name="console" />
<add name="customtracelistener" /> /// need to add new listener here
</listeners>
</source>
</sources>
<sharedListeners>
<add name="console" type="..." initializeData="..." />
<add name="customtracelistener" type="..." initializeData="..."> /// need to add custom trace listener here
<filter type="..." initializeData="Warning"/> /// with a filter
</add>
</sharedListeners>
<switches>
<add name="..." value="..." />
</switches>
</system.diagnostics>
使用ConfigurationManager,我可以轻松做到:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSection diagnostics = config.GetSection("system.diagnostics");
当我这样做时,诊断是System.Diagnostics.SystemDiagnosticsSection类型.有趣的是,我无法将诊断转换为SystemDiagnosticsSection类型,因为我无法在任何名称空间中找到它.无论如何,ConfigurationSection似乎没有任何可用于将数据写入该部分的方法.
我也不能将其强制转换为NameValueConfigurationCollection,因为诊断的基本类型为ConfigurationSection.我听说过这种技术,但似乎无法使用.
我是否必须恢复使用普通的XML来完成此任务?我真的不喜欢重新发明轮子.
解决方法:
您可以通过ConfigurationManager找到app.exe.config文件的路径,然后将配置文件作为XDocument加载.
string configPath = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath;
XDocument config = XDocument.Load(configPath);
XElement diagnostics = config.Descendants().FirstOrDefault(e => e.Name == "system.diagnostics");
if (diagnostics == default(XElement))
{
/// <system.diagnostics> element was not found in config
}
else
{
/// make changes within <system.diagnostics> here...
}
config.Save(configPath);
Trace.Refresh(); /// reload the trace configuration
进行所需的更改后,将XDocument保存回磁盘,并调用Trace.Refresh()重新加载跟踪配置.
See MSDN regarding the Trace.Refresh method here.
内容总结
以上是互联网集市为您收集整理的c#-在运行时修改app.config部分全部内容,希望文章能够帮你解决c#-在运行时修改app.config部分所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。