【ABP 源码学习】Stream 扩展

2022年6月24日 1328点热度 0人点赞 0条评论
内容纲要

处理 Stream 的一些用法。

    public static byte[] GetAllBytes(this Stream stream)
    {
        using (var memoryStream = new MemoryStream())
        {
            if (stream.CanSeek)
            {
                stream.Position = 0;
            }
            stream.CopyTo(memoryStream);
            return memoryStream.ToArray();
        }
    }

    public static async Task<byte[]> GetAllBytesAsync(this Stream stream, CancellationToken cancellationToken = default)
    {
        using (var memoryStream = new MemoryStream())
        {
            if (stream.CanSeek)
            {
                stream.Position = 0;
            }
            await stream.CopyToAsync(memoryStream, cancellationToken);
            return memoryStream.ToArray();
        }
    }

    public static Task CopyToAsync(this Stream stream, Stream destination, CancellationToken cancellationToken)
    {
        if (stream.CanSeek)
        {
            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
        );
    }

痴者工良

高级程序员劝退师

文章评论