tags:

views:

419

answers:

1

A useful convenience introduced in .NET 4 is Stream.CopyTo(Stream[, Int32]) which reads the content from the current stream and writes it to another stream.

This obviates the need for slightly tedious code such as this:

public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[32768];
    while (true)
    {
        int read = input.Read (buffer, 0, buffer.Length);
        if (read <= 0)
            return;
        output.Write (buffer, 0, read);
    }
}

Since I don't have .NET 4 installed on this machine, I was wondering if someone who has .NET 4 installed could open up Reflector and show us how the Framework Class Library team implemented this method for .NET 4.

Compare and contrast their implementation with code snippet above. In particular, I'm interested to know what default buffer size was chosen.

+4  A: 

From Reflector, it uses a fixed buffer size of 0x1000 (4096 bytes). (There is an overload where you can pass your own buffer size.) (Beta 2 build, undoubtedly subject to change as they tune things for RTM.)

The implementation is very similar to yours, modulo some shuffling around and some error checking. Reflector renders the heart of it as follows:

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);
  }
}

The error checking is basically around whether input.CanRead and output.CanWrite are both true, or either is disposed. So in answer to Benny's question this should be perfectly happy copying from a NetworkStream (or to a writable NetworkStream).

itowlson
I guess the idea is to just use exactly 1 page for the buffer?
Yuliy
It's a "happy number" for buffer sizes. It is highly unlikely to fall exactly on a page boundary.
Hans Passant