/// <summary> /// Copies one Stream to the other. The current position of each is used. /// </summary> /// <param name="src">The Stream to copy from.</param> /// <param name="dest">The Stream to copy to.</param> /// <param name="procDelegate">A delegate for processing a read chunk before it is written.</param> /// <returns>The number of bytes copied.</returns> public static long StreamCopy(Stream src, Stream dest, StreamCopyProcessor procDelegate) { if (src == null) { throw new ArgumentNullException("src"); } if (dest == null) { throw new ArgumentNullException("dest"); } // From Stack Overflow, probably const int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; long bytesCopied = 0; int bytesRead; bool continueProcessing = true; do { bytesRead = src.Read(buffer, 0, BUFFER_SIZE); if (procDelegate != null) { continueProcessing = procDelegate(buffer, bytesRead); } dest.Write(buffer, 0, bytesRead); bytesCopied += bytesRead; }while (continueProcessing && bytesRead != 0); return(bytesCopied); }
/// <summary> /// Copies a number of bytes from one Stream to the other. The current position of each is used. /// </summary> /// <param name="src">The Stream to copy from.</param> /// <param name="dest">The Stream to copy to.</param> /// <param name="length">The number of bytes to copy.</param> /// <param name="procDelegate">A delegate to process the read buffer before it's written to the destination.</param> /// <returns>Whether or not all requested bytes are copied.</returns> public static bool StreamCopy(Stream src, Stream dest, long length, StreamCopyProcessor procDelegate) { if (src == null) { throw new ArgumentNullException("src"); } if (dest == null) { throw new ArgumentNullException("dest"); } if (length == 0) { return(true); } const int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; int read; long left = length; bool continueProcessing = true; while (continueProcessing && left / buffer.Length != 0 && (read = src.Read(buffer, 0, buffer.Length)) > 0) { if (procDelegate != null) { continueProcessing = procDelegate(buffer, read); } dest.Write(buffer, 0, read); left -= read; } // Should stop if zero bytes have been read from stream although some should have been read if (length > BUFFER_SIZE && left == length) { return(false); } if (src.CanSeek && src.Position == src.Length && left != 0) { throw new EndOfStreamException(); } while (continueProcessing && left > 0 && (read = src.Read(buffer, 0, (int)left)) > 0) { if (procDelegate != null) { continueProcessing = procDelegate(buffer, read); } dest.Write(buffer, 0, read); left -= read; } return(left == 0); }