DeflateStream 复制到 MemoryStream

DeflateStream CopyTo MemoryStream

尝试压缩和解压缩 MemoryStream,但似乎 CopyTo 没有像预期的那样工作?为什么?如何解决这个问题?

public static MemoryStream Compress(MemoryStream originalStream)
{
    Console.WriteLine("Original before compressing size: {0}", originalStream.Length.ToString());
    MemoryStream compressedMemoryStream = new MemoryStream();

    using (DeflateStream deflateStream = new DeflateStream(compressedMemoryStream, CompressionMode.Compress, true))
    {
        originalStream.CopyTo(deflateStream);
    }
    Console.WriteLine("Compressed size: {0}", compressedMemoryStream.Length.ToString());
    return compressedMemoryStream;
}

public static void Decompress(MemoryStream compressedStream)
{
    Console.WriteLine("Compressed before decompressing size: {0}", compressedStream.Length.ToString());
    using (MemoryStream decompressedFileStream = new MemoryStream())
    {
         using (DeflateStream decompressionStream = new DeflateStream(compressedStream, CompressionMode.Decompress, true))
         {
              decompressionStream.CopyTo(decompressedFileStream);
         }
         Console.WriteLine("Decompressed size: {0}", decompressedFileStream.Length.ToString());
    }
}

输出:

Original before compressing size: 5184054
Compressed size: 0
Compressed before decompressing size: 0
Decompressed size: 0

CopyTo 开始从源流的当前位置 复制字节。

由于您发布的结果压缩流大小为 0,我很确定 originalStream 位于流的末尾,因此没有字节被复制/压缩。

确保位置是 0 以便它可以找到要复制并压缩到您的流中的任何数据。

如@xanatos 所述,Decompress 也是如此,因此在解压之前确保 compressedStream 也位于 0。