How to write the content of one stream into another stream in .net?

In .NET 4.0 we finally got a Stream.CopyTo method! Yay!


I'm not sure if you can directly pipe one stream to another in .NET, but here's a method to do it with an intermediate byte buffer. The size of the buffer is arbitrary. The most efficient size will depend mostly on how much data you're transferring.

static void CopyStream(Stream input, Stream output){
    byte[] buffer = new byte[0x1000];
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0) 
        output.Write(buffer, 0, read);
}

Regarding the ideal buffer size:

"When using the Read method, it is more efficient to use a buffer that is the same size as the internal buffer of the stream, where the internal buffer is set to your desired block size, and to always read less than the block size. If the size of the internal buffer was unspecified when the stream was constructed, its default size is 4 kilobytes (4096 bytes)."

Any stream-reading process will use Read(char buffer[], int index, count), which is the method this quote refers to.

http://msdn.microsoft.com/en-us/library/9kstw824.aspx (Under "Remarks").

Tags:

.Net

Stream