using System.ComponentModel; using System.IO; using System.Threading; using System.Threading.Tasks; namespace JiShe.CollectBus.Common.Extensions { public static class StreamExtensions { /// /// Gets all bytes. /// /// The stream. /// [Description("获取字节数组")] public static byte[] GetAllBytes(this Stream stream) { using (var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); return memoryStream.ToArray(); } } /// /// Gets all bytes asynchronous. /// /// The stream. /// The cancellation token. /// public static async Task GetAllBytesAsync(this Stream stream, CancellationToken cancellationToken = default) { using (var memoryStream = new MemoryStream()) { stream.Position = 0; await stream.CopyToAsync(memoryStream, cancellationToken); return memoryStream.ToArray(); } } /// /// Copies to asynchronous. /// /// The stream. /// The destination. /// The cancellation token. /// [Description("复制")] public static Task CopyToAsync(this Stream stream, Stream destination, CancellationToken cancellationToken) { stream.Position = 0; return stream.CopyToAsync( destination, 81920, //this is already the default value, but needed to set to be able to pass the cancellationToken cancellationToken ); } } }