© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•6mo ago•
3 replies
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
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
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
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
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
Optimal
), I get a random error in the middle of reading with
reader
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)
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ Reading from ClientWebSocket with BinaryReader
C#CC# / help
3y ago
BinaryReader Question
C#CC# / help
4y ago
Does C# have a JPEG compressed stream reader?
C#CC# / help
3mo ago
❔ Reading from stdin
C#CC# / help
3y ago