Friday, March 16, 2007

Stream to stream copy

John Skeet wrote an excellent article about reading binary data a while back. Thanks to John I now know that the Read method doesn't necessarily return the entire stream contents. This has saved me a bunch of trouble so far. However I run into a situation from time to time where I need to copy one stream into another. The input stream is potentially very large, so simply copying the whole thing into a byte array and then writing it to the output stream doesn't seem like a good idea. I've adopted some of John's sample code into this:
public static void StreamCopy( Stream input, Stream output )
 byte[] buffer = new byte[ 2048 ];
 int remaining = (int)input.Length;
 BinaryWriter writer = new BinaryWriter( output );
 while ( remaining > 0 )
   int read = input.Read( buffer, 0,
     ( remaining < buffer.Length ? remaining : buffer.Length ) );

   if ( read <= 0 )
     throw new EndOfStreamException( "Unexpected end of stream" );

   writer.Write( buffer );
   remaining -= read;
I can't help wondering if there is a more efficient way to do this...