Odd IOException using StreamWriter

  • Thread starter Thread starter Michael Lofgren
  • Start date Start date
M

Michael Lofgren

Hi,
(Apologies for the resend, but I forgot to add the subject previously)

Below is an excerpt from my code. When I run it, the I sometimes (one every
three times?) get a System.IO.IOException, with no error description. The
exception seems to occur when the flush occurs... With autoflushing on
Write() causes the exception, without autoflushing Flush() causes the
exception, and commenting out the Flush() results in the Close() causing the
exception.

Everytime the exception occurs, two identical lines are appended to my file
instead of one.

Can anyone tell me what is causing this, or how to track it down further?
I've referenced SR.dll in my project, it didn't improve the content of the
error message.

I am running this on CE 5, .NET 1.1 (I think).

try {
//Check directory existence
if (!Directory.Exists(eventLogPath)) {
Directory.CreateDirectory(eventLogPath);
}

StreamWriter w;
w = File.AppendText(eventLogPath + filename);
w.AutoFlush = true;
w.Write(eventstr);
w.Flush();
w.Close();
} catch (Exception x) {
MessageBox.Show("Exception thrown from EventLog.RecordEvent(): " +
x.ToString());
}

Thanks in advance,

Michael
 
A few things:-
* Firstly you are using File.AppendText but not checking that the file in
question already exists.
* Secondly consider using Path.Combine as a cleaner way of joining your path
and filename.
* Thirdly, if you are setting AutoFlush to true you don't need to call Flush
as well as this is being done for you as part of the Write - remove either
one or the other.
* Finally you should call Dispose on the stream writer once you have
finished with it.

Peter
 
Thankyou for your reply. In response to your suggestions:

- My reading of the File.AppendText() help is that if the file does not
exist, it will create it. Indeed this is what seems to happen in practice.
My problem generally occurs after several additions to the file have already
occurred.
- I will implement your Path.Combine() suggestion, however I don't believe
it will affect the issue with the IOException.
- I'm aware of the redundancy of AutoFlush and Flush... I did a number of
tests trying to identify the reason for the exception. If I called Write()
followed by Close(), the exception was generated when Close() was called. If
I added a Flush() before the Close(), the exception occurred when Flush()
was called. If I set AutoFlush to true, Write caused the exception. This
leads me to believe that the exception occurs due to flushing that occurs in
the underlying code.
- I thought you might be on to something here. I tried calling Dispose()
directly instead of waiting for the garbage collector to deal with it, but
because it is protected I can't call it without creating a new class and
inheriting StreamWriter. Is that what you had in mind?

Thanks again.
 
Back
Top