解压缩和回压缩不会返回相同的内容

时间:2018-09-05 18:25:24

标签: c# deflatestream

为什么在用DeflateStream解压缩并压缩回字节数组后,为什么没有得到相同的内容?

代码:

byte[] originalcontent = Same Byte Array Content
byte[] decompressedBytes;
byte[] compressedBackBytes;

// Decompress the original byte-array
using (Stream contentStream = new MemoryStream(originalcontent, false))
using (var zipStream = new DeflateStream(contentStream, CompressionMode.Decompress))
using (var decStream = new MemoryStream())
{
    zipStream.CopyTo(decStream);
    decompressedBytes = decStream.ToArray();
}

// Compress the byte-array back
using (var input = new MemoryStream(decompressedBytes, true))
using (var compressStream = new MemoryStream())
using (var compressor = new DeflateStream(compressStream, CompressionMode.Compress))
{
    input.CopyTo(compressor);
    compressedBackBytes = compressStream.ToArray();
}

为什么originalcontent!= compressionBackBytes?

1 个答案:

答案 0 :(得分:1)

看起来您一切正常,直到获取原始输入流并改写了包含解压缩字节的压缩器为止。您需要将压缩器字节放入CompressedBackBytes中。

您的输入(从解压缩开始)似乎将已解压缩的字节复制到其中;然后将其复制到压缩器中,压缩器将覆盖刚刚解压缩的内容。

也许你的意思是

compressedBackBytes = compressor.ToArray();