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.
In .NET 4.5.1, it uses a fixed buffer size of 81920 bytes. (Earlier versions of .NET used a fixed buffer size of 4096 bytes, and it will no doubt continue to change over time.) There is also an overload where you can pass your own buffer size.
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);
}
}
(You can now see the actual source at http://referencesource.microsoft.com/#mscorlib/system/io/stream.cs#98ac7cf3acb04bb1.)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With