从 ConfigurationManager 获取数据而不解析所有 XML

Get data from the ConfigurationManager without parsing all the XML

我想在 mi app.config 中获取跟踪侦听器配置中的标签值

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.diagnostics>
        <sources>
            <source name="System.ServiceModel.MessageLogging" switchValue="Warning,ActivityTracing">
                <listeners>
                    <add type="System.Diagnostics.DefaultTraceListener" name="Default">
                        <filter type="" />
                    </add>
                    <add name="ServiceModelMessageLoggingListener">
                        <filter type="" />
                    </add>
                </listeners>
            </source>
        </sources>
        <sharedListeners>
            <add initializeData="c:\software\app_messages.svclog" 
                 type="System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="ServiceModelMessageLoggingListener" traceOutputOptions="Timestamp">
                <filter type="" />
            </add>
        </sharedListeners>
        <trace autoflush="true" />
    </system.diagnostics>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
    <system.serviceModel>
      <diagnostics>
        <messageLogging      
          logMessagesAtTransportLevel="true"
          logMessagesAtServiceLevel="false"
          logMalformedMessages="true"
          logEntireMessage="true"
          maxSizeOfMessageToLog="65535000"
          maxMessagesToLog="500" />
      </diagnostics>

    </system.serviceModel>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

我想要的线路是:

<add initializeData="c:\software\app_messages.svclog" 

我需要修改 app_messages.svclog 并像这样读写:

string logFilePath = ConfigurationManager.sharedListeners("initializeData")

 using (var fileStream = new FileStream(logFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
 {.....

使用 xml linq :

class Program
{
    const string FILENAME = @"c:\temp\test.xml";
    static void Main(string[] args)
    {
        XDocument doc = XDocument.Load(FILENAME);

        string change = doc.Descendants("add")
                           .Where(x => x.Attribute("initializeData") != null)
                           .Select(x => (string)x.Attribute("initializeData"))
                           .FirstOrDefault();
    }     
}