Search code examples
c#.netloggingtracetracelistener

Close/reopen TraceListener created with XML config, pointing to external USB stick


I have a TraceListener object, used for logging, created in app.config that points to a location on a USB stick.

I'm getting an IOException with the message

The volume for a file has been externally altered so that the opened file is no longer valid.

when attempting to Trace.WriteLine() after I've removed the device then plugged it back in. I understand that it's happening because the handle to the open file that the Trace listener has is invalidated when I unplug it.

I've managed to thwart the IOExceptions by calling Close() on the TraceListener, but I can't figure out how to re-open the handle to that same file again. The MSDN documentation for TextWriterTraceListener.Close() method says

Calling a Write or WriteLine method after calling Close automatically reopens the stream.

But it just isn't doing it. I'm not getting further output after I close the stream.

EDIT:

Some more information

I've found that the Trace Listener is only unable to write again if, after I call Close(), I attempt to write while the drive is unplugged. If I don't write while the drive is unplugged then plug the drive again and try to write, everything works fine. I've also verified that my Trace.Listeners collection still contains my listener.


Solution

  • I found after a bunch of research that Trace.Refresh() seems to solve this problem but, from reading the original question's comments from rene, this method will re-initialize the entire Trace framework. It seems a bit heavy for what I wanted, but maybe this answer will help someone else.

    Trace.Refresh() on MSDN

    Remarks from MSDN:

    Trace configuration data is captured when the application is started. If the configuration data is changed after the application is started, call the Refresh method to update the trace configuration data.