/// <summary> /// Read all the bytes from a stream /// </summary> public static async Task<byte[]> ReadBytes(this IReadAsyncStream readStream) { using (var ms = new MemoryStream()) { await readStream.CopyToStream(ms, CancellationToken.None).ConfigureAwait(false); return ms.ToArray(); } }
/// <summary> /// Copies any stream into a local MemoryStream /// </summary> /// <param name = "stream">The source stream.</param> /// <returns>The copied memory stream.</returns> public static MemoryStream CopyToMemory(this Stream stream) { MemoryStream memoryStream = new MemoryStream((int) stream.Length); stream.CopyToStream(memoryStream); return memoryStream; }
/// <summary> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </summary> public static Result<MemoryStream> ToMemoryStream(this Stream stream, long length, Result<MemoryStream> result) { MemoryStream copy; if(stream is MemoryStream) { var mem = (MemoryStream)stream; copy = new MemoryStream(mem.GetBuffer(), 0, (int)mem.Length, false, true); result.Return(copy); } else { copy = new MemoryStream(); stream.CopyToStream(copy, length, new Result<long>(TimeSpan.MaxValue)).WhenDone( v => { copy.Position = 0; result.Return(copy); }, result.Throw ); } return result; }