Stream流转到byte数组

前言,需要对一个下载下来的stream进行多次读操作。这个时候是无法确定stream的长度,无法进行seek复位操作,所以需要转化为byte数组

private byte[] StructureBytes(Stream stream)
{
    int bufferSize = 10240;
    long writtenBytes = 0L;
    var byteArrs = new List<byte[]>();
    while (true)
    {
        byte[] buffer = new BinaryReader(stream).ReadBytes(bufferSize);
        writtenBytes += buffer.Length;
        byteArrs.Add(buffer);
        // If the end of the report is reached, break out of the 
        // loop.
        if (buffer.Length != bufferSize)
        {
            break;
        }
    }

    byte[] bytes = new byte[writtenBytes];
    int times = (int)(writtenBytes / 10240);
    for (var i = 0; i <= times; i++)
    {
        if (i < times)
        {
            Buffer.BlockCopy(byteArrs[i], 0, bytes, i * 10240, 10240);
            continue;
        }
        if ((int)(writtenBytes % 10240) == 0) break;
        Buffer.BlockCopy(byteArrs[i], 0, bytes, i * 10240, (int)(writtenBytes % 10240));
    }
    return bytes;
}

在拿到Byte[]数组之后,就可以任意操作
例如

private int ValueStartRowIndex(byte[] bytes)
{
    if (_totalRows == 0)
        return -1;

    using var sr = new StreamReader(new MemoryStream(bytes), Encoding.UTF8);
    var index = 0;
    while (!sr.EndOfStream)
    {
        var line = sr.ReadLine();
        if (string.IsNullOrWhiteSpace(line))
            return index + 2;
        else
            index++;
    }
    return -1;
}

只需要传递byte数组就可以。


版权声明:本文为qq_36479244原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。