c# - DeflateStream 复制到 MemoryStream

标签 c# memorystream deflate

尝试压缩和解压缩 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。

关于c# - DeflateStream 复制到 MemoryStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51122458/

相关文章:

C# 你打算调用方法吗

java - 处理给定数据集时,如何为 zlib 'setDictionary' 找到好的/最佳字典?

JavaScript 压缩实现

c# - 如何从 Asp.Net Core 中的 IActionResult 将 MemoryStream 作为 Excel 文件返回

c# - Google Protocol Buffers - 序列化为字节数组

c# - c# 中的 java.util.zip.deflater 等价物

c# - 如何修复错误代码 CS1503?

c# - ASP.NET Web Forms 4.5 模型绑定(bind),其中模型包含集合

c# - 有没有一种简写的方法来声明一个控件并订阅它的事件处理程序?

.net - 使用 MemoryStream 保存 .docx 文件 C#