Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StreamWriter not writing out the last few characters to a file

Tags:

c#

iostream

We are having an issue with one server and it's utilization of the StreamWriter class. Has anyone experienced something similar to the issue below? If so, what was the solution to fix the issue?

  using( StreamWriter logWriter = File.CreateText( logFileName ) )
  {
    for (int i = 0; i < 500; i++)
      logWriter.WriteLine( "Process completed successfully." );
  } 

When writing out the file the following output is generated:

  Process completed successfully.
  ...  (497 more lines)
  Process completed successfully.
  Process completed s

Tried adding logWriter.Flush() before close without any help. The more lines of text I write out the more data loss occurs.

like image 768
Rob Packwood Avatar asked Oct 07 '10 18:10

Rob Packwood


People also ask

Does StreamWriter overwrite?

StreamWriter(String, Boolean) Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.

What is the difference between FileStream and StreamWriter?

Specifically, a FileStream exists to perform reads and writes to the file system. Most streams are pretty low-level in their usage, and deal with data as bytes. A StreamWriter is a wrapper for a Stream that simplifies using that stream to output plain text.

Where does StreamWriter write to?

StreamWriter contains methods to write to a file synchronously (Write and WriteLine) or asynchronously (WriteAsync and WriteLineAsync). File provides static methods to write text to a file such as WriteAllLines and WriteAllText, or to append text to a file such as AppendAllLines, AppendAllText, and AppendText.

Do I need to close StreamWriter?

You must call Close to ensure that all data is correctly written out to the underlying stream. Following a call to Close, any operations on the StreamWriter might raise exceptions.


5 Answers

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;

like image 129
zero Avatar answered Nov 07 '22 19:11

zero


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();
}
like image 43
Bonshington Avatar answered Nov 07 '22 18:11

Bonshington


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.
like image 1
Henk Holterman Avatar answered Nov 07 '22 20:11

Henk Holterman


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();
like image 1
Dr. Wily's Apprentice Avatar answered Nov 07 '22 18:11

Dr. Wily's Apprentice


In my case, this is what I found with output file

Case 1: Without Flush() and Without Close()

Character Length = 23,371,776

Case 2: With Flush() and Without Close()

logWriter.flush()

Character Length = 23,371,201

Case 3: When propely closed

logWriter.Close()

Character Length = 23,375,887 (Required)

So, In order to get proper result, always need to close Writer instance.

like image 1
Manish Jain Avatar answered Nov 07 '22 19:11

Manish Jain