public static void CopyUpTo(
this Stream source, Stream destination, long maxBytes, int bufferSize = 1024)
{
ArgumentGuard.NotNull(source, nameof(source));
ArgumentGuard.NotNull(destination, nameof(destination));
ArgumentGuard.GreaterOrEqual(maxBytes, -1, nameof(maxBytes));
if (maxBytes == -1)
{
maxBytes = long.MaxValue;
}
byte[] buffer = new byte[bufferSize];
var totalRead = 0;
int bytesRead;
while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
{
totalRead += bytesRead;
if (totalRead > maxBytes)
{
throw new ArgumentException(
"source stream contains more than {0} bytes".Fmt(maxBytes));
}
destination.Write(buffer, 0, bytesRead);
}
}