private static async Task <byte[]> InternalReadAllBytesUnknownLengthAsync(SafeFileHandle sfh, CancellationToken cancellationToken) { byte[] rentedArray = ArrayPool <byte> .Shared.Rent(512); try { int bytesRead = 0; while (true) { if (bytesRead == rentedArray.Length) { uint newLength = (uint)rentedArray.Length * 2; if (newLength > Array.MaxLength) { newLength = (uint)Math.Max(Array.MaxLength, rentedArray.Length + 1); } byte[] tmp = ArrayPool <byte> .Shared.Rent((int)newLength); Buffer.BlockCopy(rentedArray, 0, tmp, 0, bytesRead); byte[] toReturn = rentedArray; rentedArray = tmp; ArrayPool <byte> .Shared.Return(toReturn); } Debug.Assert(bytesRead < rentedArray.Length); int n = await RandomAccess.ReadAtOffsetAsync(sfh, rentedArray.AsMemory(bytesRead), bytesRead, cancellationToken).ConfigureAwait(false); if (n == 0) { return(rentedArray.AsSpan(0, bytesRead).ToArray()); } bytesRead += n; } } finally { sfh.Dispose(); ArrayPool <byte> .Shared.Return(rentedArray); } }
private static async Task <byte[]> InternalReadAllBytesAsync(SafeFileHandle sfh, int count, CancellationToken cancellationToken) { using (sfh) { int index = 0; byte[] bytes = new byte[count]; do { int n = await RandomAccess.ReadAtOffsetAsync(sfh, bytes.AsMemory(index), index, cancellationToken).ConfigureAwait(false); if (n == 0) { ThrowHelper.ThrowEndOfFileException(); } index += n; } while (index < count); return(bytes); } }