.Net 6 System.IO.Compression 问题是否有任何解决方法。 DeflateStream.Read 方法在 .Net 6 中工作不正确,但在旧版本中工作正常

Is there any workaround for .Net 6 System.IO.Compression issue. DeflateStream.Read method works incorrect in .Net 6, but works fine in older versions

这里是真实项目的代码,采用了问题,所以一些数据是硬编码的:

   static void Main(string[] args)
    {
        Console.WriteLine("Starting. " + Environment.Version);
        using (var stream = new FileStream(@"stream_test.txt", FileMode.Open))
        {
            stream.Position = 0;

            // .NET implements Deflate (RFC 1951) but not zlib (RFC 1950),
            // so we have to skip the first two bytes.
            stream.ReadByte();
            stream.ReadByte();

            var zipStream = new DeflateStream(stream, CompressionMode.Decompress, true);

            // Hardcoded length from real project. In the previous .Net versions this is size of final result
            long bytesToRead = (long)262 * 350;

            var buffer = new byte[bytesToRead];
            int bytesWereRead = zipStream.Read(buffer, 0, (int)bytesToRead);

            if (bytesWereRead != bytesToRead)
            {
                throw new Exception("ZIP stream was not fully decompressed.");
            }

            Console.WriteLine("Ok");
            Console.ReadKey();
        }
    }

解压问题并未出现在每个流上,因此可以在带有项目代码的 GitHub 上找到输入文件。 https://github.com/dimsa/Net6DeflateStreamIssue/tree/main/DeflateStreamTest

此代码在正常上有效:

.NET 6 失败。 Net 6中解压后的数据长度不正确

是否有任何解决方法,或者应该使用其他压缩库?

DeflateStream 在 .NET 6 中的运行方式发生了重大变化。您可以阅读更多相关信息和建议的操作 in this Microsoft documentation

基本上,您需要包装 .Read 操作并检查读取的长度与预期长度,因为操作现在可能 return 在读取完整长度之前。您的代码可能如下所示(基于文档中的示例):

int totalRead = 0;
var buffer = new byte[bytesToRead];
while (totalRead < buffer.Length)
{
    int bytesRead = zipStream.Read(buffer.Slice(totalRead));
    if (bytesRead == 0) break;
    totalRead += bytesRead;
}