为什么压缩小文件的gzip / deflate导致许多尾随零?

我正在使用以下代码在C#中压缩一个小的(~4kB)HTML文件。

byte[] fileBuffer = ReadFully(inFile, ResponsePacket.maxResponsePayloadLength); // Read the entire requested HTML file into a memory buffer inFile.Close(); // Close the requested HTML file byte[] payload; using (MemoryStream compMS = new MemoryStream()) // Create a new memory stream to hold the compressed HTML data { using (GZipStream gzip = new GZipStream(compMS, CompressionMode.Compress)) // Create a new GZip object pointing to the empty memory stream { gzip.Write(fileBuffer, 0, fileBuffer.Length); // Compress the file buffer and write it to the empty memory stream gzip.Close(); // Close the GZip object } payload = compMS.GetBuffer(); // Write the compressed file buffer data in the memory stream to a byte buffer } 

得到的压缩数据约为2k,但其中大约一半只是零。 这是一个非常带宽敏感的应用程序(这就是为什么我首先要压缩4kB的原因),所以额外的1kB零点浪费了宝贵的空间。 我最好的猜测是压缩算法将数据填充到块边界。 如果是这样,有没有办法覆盖此行为或更改块大小? 我使用vanilla .NET GZipStream和zlib的GZipStream以及DeflateStream得到了相同的结果。

错误的MemoryStream方法。 GetBuffer()返回底层缓冲区,它总是比流中的数据更大(或完全一样大)。 效率很高,因为不需要复制。

但是你需要ToArray()方法。 或者使用Length属性。