I found a code snippet online for logging with rollover at midnight to manage the log files so they would be manageable, but running into an error that happens from time to time that I can't find a solution to or rather I might've stumbled upon a solution, but don't know how to implement it. It's using a StreamWriter to write the files.
Not every time, but often it gives an ObjectDisposed exception "Can't open closed file.". The part of the class that is responsible for closing the previous and creating a new file is:
private void checkRollover()
{
// If the date has changed, close the current stream and create a new file for today's date
if (_currentDate.CompareTo(System.DateTime.Today) != 0)
{
try
{
_traceWriter.Close();
_traceWriter.Dispose();
_traceWriter = new StreamWriter(generateFilename(), true);
}
catch (Exception ex)
{
MessageBox.Show("This error: " + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
Is it because of the .dispose at the end as .close does this already or might it be something else? As I said, really stumped by this, any advice on why this might be happening is appreciated. If it's needed I can post the whole class to here.
EDIT Couldn't get the error to happen again, but now it did. I also removed the _tracewriter.Dispose() from there
System.NullReferenceException: Object reference not set to an instance of an object.
at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
at System.IO.StreamWriter.Dispose(Boolean disposing)
at System.IO.StreamWriter.Close()
at FixInterface.RollOverTextWriter.checkRollover()