无法使用GZipStream解压缩文件(不使用CopyToAsync)

时间:2017-12-12 09:42:46

标签: c# gzipstream

我正在尝试使用MemoryStream / ReadAsync解压缩WriteAsync,但它无效。

int bufferSize = 8192;
using (var memoryStream = new MemoryStream())
using (var fileStream = new FileStream(destinationFilename, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
{
    // ... populate the MemoryStream ...
    memoryStream.Position = 0;

    using (var gzipStream = new GZipStream(memoryStream, CompressionMode.Decompress, true))
    {
        ////await gzipStream.CopyToAsync(fileStream);

        byte[] buffer = new byte[bufferSize];

        while (await gzipStream.ReadAsync(buffer, 0, bufferSize) > 0)
        {
            await fileStream.WriteAsync(buffer, 0, bufferSize);
        }
    }

    await fileStream.FlushAsync();
}

gzipStream.CopyToAsync有效但不是另一种方式。为什么呢?

感谢。

1 个答案:

答案 0 :(得分:0)

ReadAsync返回读取的字节数 - 您忽略了该数字。你只能WriteAsync你先读取的确切字节数。