Using GZipStream
shouldn't add an excessive amount of trailing zeros.
But if you use MemoryStream
incorrectly, it can cause this effect. It internally uses a byte[]
to store the data. This internal buffer can be larger than the data written so far to reduce the number of allocations. If you use GetBuffer()
you get back the full array, it's your own responsibility to only use the first Length
bytes of it.
Alternatively you can call ToArray()
which returns a new byte array with exactly Length
bytes.
To quote the documentation for GetBuffer()
:
Note that the buffer contains allocated bytes which might be unused. For example, if the string
"test"
is written into theMemoryStream
object, the length of the buffer returned fromGetBuffer
is 256, not 4, with 252 bytes unused. To obtain only the data in the buffer, use theToArray
method; however,ToArray
creates a copy of the data in memory.