Stream.CopyTo

Here's a small snippet I use a lot when working with streams. It simply copies content from one stream to the other in chunks of 4 KB. It is so handy that the BCL team added it to the stream class in .NET 4.0.

static long CopyTo(this Stream input, Stream output)  
{
    if (!input.CanRead || !output.CanWrite)
        throw new InvalidOperationException("Stream state");
    const int bufferSize = 1024 * 4;
    byte[] buffer = new byte[bufferSize];
    int read;
    long sum = 0;
    while ((read = input.Read(buffer, 0, bufferSize)) != 0)
    {
        output.Write(buffer, 0, read);
        sum += read;
    }
    return sum;
}
Google
m@kli.dk @klinkby RSS feed  GitHub