c# - 在运行时修改 app.config <system.diagnostics> 部分

标签 c# .net configuration app-config configurationmanager

我需要修改 <configuration><system.diagnostics>app.config在运行时,这样我就可以:

  1. 添加 CustomTraceListener<sharedListeners>下元素,需要特殊 initializeData这只能在运行时确定。

  2. 添加 CustomTraceListener <source><listeners> 下现有源的共享监听器元素。

  3. 坚持 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");

当我这样做时,diagnosticsSystem.Diagnostics.SystemDiagnosticsSection类型。有趣的是我不能投 diagnosticsSystemDiagnosticsSection 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() 重新加载跟踪配置。

See MSDN regarding the Trace.Refresh method here .

关于c# - 在运行时修改 app.config <system.diagnostics> 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35619525/

相关文章:

.net - 将 JSON 转换为 .NET 数据集

c# - 如何将字符串转换为 System.Net.IPAddress

css - 如何允许在 Froala HTML 所见即所得编辑器中使用内部 css

language-agnostic - 如何动态配置应用程序?

go - 如何使用 golang viper Watchconfig & onConfigChange

c# - 使用 IOptions 模式时,如何使选项对象的属性成为强制属性?

c# - 隐藏 app.config

c# - 如何制作 XML 或 JSON 配置文件并在 JavaScript 中反序列化?

c# - 是早点返回更快还是让代码完成?

c# - zip 文件中 unicode 文件名的兼容性问题