static void CopyStream(Stream source, Stream dest, long length, Action<long> progressCallback)
{
var buffer = new byte[8192];
if (progressCallback != null)
progressCallback(0);
long totalBytesRead = 0;
while (totalBytesRead < length) // reuse this local var
{
int bytesRead = source.Read(buffer, 0, buffer.Length);
if (bytesRead > 0)
dest.Write(buffer, 0, bytesRead);
else
throw new Exception("Unexpected end of stream while copying.");
totalBytesRead += bytesRead;
if (progressCallback != null)
progressCallback(totalBytesRead);
}
}