Akamai.Utils.ExtensionMethods.ReadExactly C# (CSharp) Method

ReadExactly() public static method

Reads a stream up to @maxCount number of bytes. Less bytes will be returned if the end of the file is reached.
public static ReadExactly ( this stream, long maxCount ) : byte[]
stream this the stream to read
maxCount long the maximum number of bytes to read
return byte[]
        public static byte[] ReadExactly(this Stream stream, long maxCount)
        {
            using (MemoryStream result = new MemoryStream())
            {
                byte[] buffer = new byte[1024 * 1024];
                int bytesRead = 0;
                long leftToRead = maxCount;

                while ((bytesRead = stream.Read(buffer, 0, leftToRead > int.MaxValue ? int.MaxValue : Convert.ToInt32(leftToRead))) != 0)
                {
                    leftToRead -= bytesRead;
                    result.Write(buffer, 0, bytesRead);
                }

                return result.ToArray();
            }
        }