public static long CopyAndCloseSource(this Stream source, Stream destination, long? size)
{
int reads = 0;
long total = 0;
int bufferSize;
using (source)
{
if (size.HasValue && size < 0)
{
size = null;
}
if (size == null || (size.HasValue && size.Value > maxSize))
{
bufferSize = maxSize; // max socket read
}
else
{
bufferSize = (int)size.Value;
}
byte[] buffer;
int got;
if (destination == null)
{
buffer = drainBuffer;
while ((got = source.Read(buffer, 0, buffer.Length)) > 0)
{
++reads;
total += got;
if (size != null && total == size.Value)
{
break;
}
}
}
else
{
buffer = new byte[bufferSize];
while ((got = source.Read(buffer, 0, buffer.Length)) > 0)
{
++reads;
destination.Write(buffer, 0, got);
total += got;
if (size != null && total == size.Value)
{
break;
}
}
destination.Flush();
}
}
return total;
}
public static byte[] ReadAllBytes(this Stream source, long? length)