Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to do StreamWriter.flush()?

Suppose this C# code:

using (MemoryStream stream = new MemoryStream()) {     StreamWriter normalWriter = new StreamWriter(stream);     BinaryWriter binaryWriter = new BinaryWriter(stream);      foreach(...)     {         binaryWriter.Write(number);         normalWriter.WriteLine(name); //<~~ easier to reader afterward.     }      return MemoryStream.ToArray(); } 

My questions are:

  1. Do I need to use flush inside the loop to preserve order?
  2. Is returning MemoryStream.ToArray() legal? I using the using-block as a convention, I'm afraid it will mess things up.
like image 829
Nefzen Avatar asked Jun 29 '09 16:06

Nefzen


People also ask

What does flush do in StreamWriter?

Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.

Do I need to flush MemoryStream?

You don't need to use Flush on the MemoryStream , as it's not buffering anything that is written to any other source. There is simply nothing to flush anywhere. The Flush method is only present in the MemoryStream object because it inherits from the Stream class.

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.


1 Answers

Scratch the previous answer - I hadn't noticed that you were using two wrappers around the same stream. That feels somewhat risky to me.

Either way, I'd put the StreamWriter and BinaryWriter in their own using blocks.

Oh, and yes, it's legal to call ToArray() on the MemoryStream - the data is retained even after it's disposed.

If you really want to use the two wrappers, I'd do it like this:

using (MemoryStream stream = new MemoryStream()) {     using (StreamWriter normalWriter = new StreamWriter(stream))     using (BinaryWriter binaryWriter = new BinaryWriter(stream))     {         foreach(...)         {             binaryWriter.Write(number);             binaryWriter.Flush();             normalWriter.WriteLine(name); //<~~ easier to read afterward.             normalWriter.Flush();         }     }         return MemoryStream.ToArray(); } 

I have to say, I'm somewhat wary of using two wrappers around the same stream though. You'll have to keep flushing each of them after each operation to make sure you don't end up with odd data. You could set the StreamWriter's AutoFlush property to true to mitigate the situation, and I believe that BinaryWriter currently doesn't actually require flushing (i.e. it doesn't buffer any data) but relying on that feels risky.

If you have to mix binary and text data, I'd use a BinaryWriter and explicitly write the bytes for the string, fetching it with Encoding.GetBytes(string).

like image 165
Jon Skeet Avatar answered Sep 30 '22 17:09

Jon Skeet