MemoryStream.WriteTo(Stream destinationStream) versus Stream.CopyTo(Stream destinationStream)

Writwick picture Writwick · May 19, 2012 · Viewed 16.1k times · Source

Which one is better : MemoryStream.WriteTo(Stream destinationStream) or Stream.CopyTo(Stream destinationStream)??

I am talking about the comparison of these two methods without Buffer as I am doing like this :

Stream str = File.Open("SomeFile.file");
MemoryStream mstr = new MemoryStream(File.ReadAllBytes("SomeFile.file"));

using(var Ms = File.Create("NewFile.file", 8 * 1024))
{
    str.CopyTo(Ms) or mstr.WriteTo(Ms);// Which one will be better??
}

Update

Here is what I want to Do :

  • Open File [ Say "X" Type File]
  • Parse the Contents
  • From here I get a Bunch of new Streams [ 3 ~ 4 Files ]
  • Parse One Stream
  • Extract Thousands of files [ The Stream is an Image File ]
  • Save the Other Streams To Files
  • Editing all the Files
  • Generate a New "X" Type File.

I have written every bit of code which is actually working correctly..

But Now I am optimizing the code to make the most efficient.

Answer

Hans Passant picture Hans Passant · May 19, 2012

It is an historical accident that there are two ways to do the same thing. MemoryStream always had the WriteTo() method, Stream didn't acquire the CopyTo() method until .NET 4.

The MemoryStream.WriteTo() version looks like this:

public virtual void WriteTo(Stream stream)
{
    // Exception throwing code elided...
    stream.Write(this._buffer, this._origin, this._length - this._origin);
}

The Stream.CopyTo() implementation like this:

private void InternalCopyTo(Stream destination, int bufferSize)
{
    int num;
    byte[] buffer = new byte[bufferSize];
    while ((num = this.Read(buffer, 0, buffer.Length)) != 0)
    {
        destination.Write(buffer, 0, num);
    }
}

Stream.CopyTo() is more universal, it works for any stream. And helps programmers that fumble copying data from, say, a NetworkStream. Forgetting to pay attention to the return value from Read() was a very common bug. But it of course copies the bytes twice and allocates that temporary buffer, MemoryStream doesn't need it since it can write directly from its own buffer. So you'd still prefer WriteTo(). Noticing the difference isn't very likely.