reading TraceListener initializedata property from config .NET 1.1

点点圈 提交于 2019-12-11 10:47:22

问题


I have the following config file:

  <system.diagnostics>
    <trace autoflush="true" indentsize="1" >
      <listeners>
        <add name="dbgTrace" type="System.Diagnostics.TextWriterTraceListener" initializeData="C:\MyLogs\MyApp\Logs\LogFile.log" />
      </listeners>
    </trace>
  </system.diagnostics> 

So I can read the tracelisteners collection like this:

TraceListenerCollection tlc = System.Diagnostics.Trace.Listeners;

and get the TraceListener from it, but the problem is, that I can not access initializeData property. There are only Name, Type, IndentLevel as public properties.

Is there any workaround?


回答1:


Done using System.Reflection:

FieldInfo fInfo = OurListener.GetType().GetField("initializeData", BindingFlags.NonPublic | BindingFlags.Instance); 
string filePath = (string)fInfo.GetValue(OurListener);



回答2:


var listener = (TextWriterTraceListener)Trace.Listeners["dbgTrace"];
var writer = (StreamWriter)listener.Writer;
var stream = (FileStream)writer.BaseStream;
Console.WriteLine(stream.Name);



回答3:


The constructor overload that has one 'name' parameter is called if the 'initializeData' attribute is specified in the config file, and that one constructor parameter passes the 'initializeData' attribute value. Also the value passed in the 'name' parameter is assigned to the 'Name' property of the TraceListener (instead of the value of the 'name' attribute in the config file).



来源:https://stackoverflow.com/questions/1769772/reading-tracelistener-initializedata-property-from-config-net-1-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!