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

Viewed 763

Here is the code from the real project, adopted for the question, so some data is hardcoded:

   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();
        }
    }

Issue with the decompressing appears not on the each stream so the input file can be found on the GitHub with the project code. https://github.com/dimsa/Net6DeflateStreamIssue/tree/main/DeflateStreamTest

This code works fine on:

  • .NET Framework (was tested on 2.0, 3.5, 4)
  • .NET Standard 2.1 and
  • .NET 5

.NET 6 fails. The decompressed data in the Net 6 has the incorrect length.

Is there any workaround, or should be used another compression libraries?

2 Answers

There was a breaking change to the way DeflateStream operates in .NET 6. You can read more about it and the recommended actions in this Microsoft documentation.

Basically, you need to wrap the .Read operation and check the length read versus the expected length because the operation may now return before reading the full length. Your code might look like this (based on the example in the documentation):

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;
}

Another work around for this. Just a different way.

 var totalRead = 0;
 var byteRead = 0;
 var buffer = new byte[dataLength];
 while (totalRead < buffer.Length)
 {
  byteRead = gZipStream.Read(buffer, totalRead, buffer.Length - totalRead);
  if (byteRead == 0) break;
  totalRead += byteRead;
 }
Related