StreamWriter not writing out the last few characters to a file

sometimes even u call flush(), it just won't do the magic. becus Flush() will cause stream to write most of the data in stream except the last block of its buffer.

try
{
 // ... write method
 // i dont recommend use 'using' for unmanaged resource
}
finally
{
 stream.Flush();
 stream.Close();
 stream.Dispose();
}

Had a very similar issue myself. I found that if I enabled AutoFlush before doing any writes to the stream and it started working as expected. logWriter.AutoFlush = true;


This certainly appears to be a "flushing" problem to me, even though you say you added a call to Flush(). The problem may be that your StreamWriter is just a wrapper for an underlying FileStream object.

I don't typically use the File.CreateText method to create a stream for writing to a file; I usually create my own FileStream and then wrap it with a StreamWriter if desired. Regardless, I've run into situations where I've needed to call Flush on both the StreamWriter and the FileStream, so I imagine that is your problem.

Try adding the following code:

            logWriter.Flush();
            if (logWriter.BaseStream != null)
                logWriter.BaseStream.Flush();

Cannot reproduce this.

Under normal conditions, this should not and will not fail.

  • Is this the actual code that fails ? The text "Process completed" suggests it's an extract.
  • Any threading involved?
  • Network drive or local?
  • etc.

Tags:

C#

Iostream