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

kha*_*osh 4 .net c# configuration configurationmanager app-config

我需要在运行时修改 a 的<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>
Run Code Online (Sandbox Code Playgroud)

使用ConfigurationManager我可以轻松做到:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSection diagnostics = config.GetSection("system.diagnostics");
Run Code Online (Sandbox Code Playgroud)

当我这样做时,diagnostics是一种System.Diagnostics.SystemDiagnosticsSection类型。有趣的是,我无法强制diagnostics转换为SystemDiagnosticsSection类型,因为我无法在任何命名空间中找到它。无论如何,ConfigurationSection似乎没有任何方法可用于将数据写入该部分。

我也不能将它转换为 aNameValueConfigurationCollection因为diagnostics基本类型是ConfigurationSection. 我听说过这种技术,但似乎我不能使用它。

我是否必须恢复使用普通的 XML 来完成此操作?我真的不喜欢重新发明轮子。

kha*_*osh 5

您可以通过 找到app.exe.config文件的路径ConfigurationManager,然后将配置文件作为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
Run Code Online (Sandbox Code Playgroud)

完成所需的更改后,保存 XDocument回磁盘,然后调用Trace.Refresh()以重新加载跟踪配置。

有关Trace.Refresh此处的方法,请参阅 MSDN