C#C
C#5mo ago
swagrid

✅BinaryReader reads garbage when reading from compressed stream

This is a weird one - I think. So I have a rather complex data type that I write to and load from disk. I'm using a ZipArchive to get some data compression.

Writing basically looks like this:
using var archive = new ZipArchive(someFileStream, ZipArchiveMode.Create, leaveOpen: true);
using var stream = archive.CreateEntry("myentry.txt", CompressionLevel.NoCompression).Open();
using var writer = new BinaryWriter(stream);
// serialize all data using writer

and reading like this:
using var archive = new ZipArchive(someFileStream, ZipArchiveMode.Read, leaveOpen: true);
using var stream = archive.GetEntry("myentry.txt").Open();
using var reader = new BinaryReader(stream);
// deserialize all data using reader


The code above works fine as long as I have NoCompression specified. I can successfully write and then read the file back. However, as soon as I change the compression level to anything else (like Optimal), I get a random error in the middle of reading with reader where it tries to read the length of an array and it reads it as a billion or something (where it should be like 100). I've gone through it with the debugger and all data up to that point is read correctly. I also don't think this is a new code path it runs into the first time. The same code has been called multiple times already before running into the error.

(more details in thread)
Was this page helpful?