Applitools.Utils.CommonUtils.CopyUpTo C# (CSharp) Method

CopyUpTo() public static method

Copies up to the specified maximal number of bytes to the destination stream.
Thrown if the source stream contains more than /// maxBytes bytes
public static CopyUpTo ( Stream source, Stream destination, long maxBytes, int bufferSize = 1024 ) : void
source Stream Source stream
destination Stream Destination stream
maxBytes long Maximal number of bytes to copy or -1 to allow /// any number of bytes to be copied
bufferSize int Size of chunks read and written
return void
        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);
            }
        }