I'm creating a trace listener like this:
// Setup log tracing.
Trace.Listeners.Add(new TextWriterTraceListener(MyLogPath));
Trace.AutoFlush = true;
Trace.WriteLine(DateTime.Now.ToString() + "-" + " Program started");
When I detect the file has got too large, I'm wanting to truncate it (or rather, take the last N lines only). In order to do this, I want to read the file in, but it seems no-matter what I do the trace listener has a lock on it, i.e. trying to remove the trace listener and dispose of its stream like this:
// Clear logging.
Trace.Listeners[0].Close();
Trace.Listeners[0].Dispose();
Trace.Listeners.Clear();
, before reading it in like this:
// Read in existing log.
string[] lines = File.ReadAllLines(MyLogPath);
, gives me an IO exception (file is in use by another process).
Any thoughts?
Well the reason you can't re-open the file once it's opened by the TraceWriter is because it opens it with a Share Mode of 'Read' (per Process Monitor). That share mode means you can't re-open it (create a new handle) with write access.
However, closing the TraceListener does close the underlying stream. The problem is likely that you are closing the wrong listener.
Don't forget that there is always a DefaultTraceListener created at process launch unless you explicitly remove it.
So the correct version of your code should be:
Trace.Listeners[1].Close();
Trace.Listeners[1].Dispose();
Trace.Listeners.Clear();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With