how to obtain filename behind trace listener using TraceSource

G

Guest

I am using a TraceSource object configured via app.config. In order to delete
the old file before starting the new trace, I need to obtain the filename
from the listener. What am I doing wrong in the following sample:

Dim trc As New TraceSource("HappySource")
‘filename returns Nothing:
Dim filename As String = _
trc.Listeners.Item("myTextListener").Attributes("initializeData")

app.config part:
<sources>
<source name="HappySource" switchName="HappySwitch">
<listeners>
<add name="myTextListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="TextWriterOutput.txt"
traceOutputOptions="DateTime" />
<remove name="Default"/>
</listeners>
</source>

thank you very much. herbert
 
D

Dave Sexton

Hi Herbert,

1. You can load the config file into an XmlDocument object and traverse the
elements or use XPath to extract the value.
2. You can store the file name in application Settings and extract it at
runtime - construct the TextWriterTraceListener at runtime as well
3. I haven't tried this myself but it may work (C#, because I forget how to
properly cast in VB):

// get a strong-typed reference to the listener
TextWriterTraceListener textWriterTL =
(TextWriterTraceListener) trc.Listeners["myTextListener"];

// get the derived StreamWriter (note: if this doesn't work then look at a
// debugger watch window to determine the actual Type of the Writer
StreamWriter writer = (StreamWriter) textWriterTL.Writer;

// get the FileStream from the writer
FileStream stream = (FileStream) writer.BaseStream;

// get the name of the file that was passed into the FileStream
string fileName = stream.Name;

It's quite possible that the last line won't work if the FileStream was
constructed from a file handle, so you'll have to test it and hope for the
best.

It's also possible that you won't be able to clear the file if it has already
been opened by the TextWriterTraceListener, in which case option #2 will be
your best choice.

GL
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top