Search code examples
c#.netstreammemorystream

Should I use Stream.Flush before Stream.CopyTo?


I have MemoryStream that I'm filling up with some data using StreamWriter. At the end I want to dump it to different stream (not always file).

Should I call Stream.Flush before using Steram.CopyTo method?


Solution

  • You never need to call Flush on a memory stream, because the operation does nothing. If you look at the source, the implementation is empty. You do need to rewind the stream after writing.

    However, you need to flush the StreamWriter, to make sure that all the data is pushed into the memory stream before you start copying it.

    You can use this pattern with StreamWriter writing to memory stream to avoid explicit flushing:

    MemoryStream memStream = ...
    using (StreamWriter wr = new StreamWriter(memStream)) {
        ... // Do the writing
    }
    memStream.Position = 0; // Rewind
    // At this point `memStream` has all data pushed into it,
    // and is positioned at zero, so it's ready to be copied.