我需要修改 <configuration><system.diagnostics>
节app.config
在运行时,这样我就可以:
添加
CustomTraceListener
在<sharedListeners>
下元素,需要特殊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");
当我这样做时,diagnostics
是 System.Diagnostics.SystemDiagnosticsSection
类型。有趣的是我不能投 diagnostics
到 SystemDiagnosticsSection
type 因为我在任何命名空间中都找不到它。不管怎样,ConfigurationSection
似乎没有任何方法可用于将数据写入该部分。
我也无法将其转换为 NameValueConfigurationCollection
因为diagnostics
基本类型是 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()
重新加载跟踪配置。
关于c# - 在运行时修改 app.config <system.diagnostics> 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35619525/