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 6 fails. The decompressed data in the Net 6 has the incorrect length.
Is there any workaround, or should be used another compression libraries?
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;
}