Do I need to do StreamWriter.flush()?

Nefzen picture Nefzen · Jun 29, 2009 · Viewed 27.8k times · Source

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.

Answer

Jon Skeet picture Jon Skeet · Jun 29, 2009

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).