【问题标题】:How to convert a compressed stream to an uncompressed stream in c# using GZipStream如何使用 GZipStream 在 C# 中将压缩流转换为未压缩流
【发布时间】:2016-11-29 10:28:24
【问题描述】:

根据各种示例,我已经能够将内存流转换为压缩流,然后转换为字节数组以保存在数据库中,但我在采用另一种方式时遇到了麻烦。这是我到目前为止所得到的......

...
using (MemoryStream compressedStream = new MemoryStream()) {
    ...some code that builds the compressedStream for an undetermined
    number of byteArrays from a database
    using (MemoryStream uncompressedStream = new MemoryStream()) {
        // method 1
        using (GZipStream unzippedStream = new GZipStream(compressedStream, CompressionMode.Decompress)) {
            unzippedStream.CopyTo(uncompressedStream);
        }
        // method 2
        using (GZipStream unzippedStream = new GZipStream(uncompressedStream, CompressionMode.Decompress)) {
            compressedStream.CopyTo(unzippedStream);
        }
        ... do something with uncompressedStream
    }
}

方法 1 接缝遵循我在这里看到的示例,但导致错误“流不支持写入”

方法 2 接缝更有意义,但未压缩的流始终为空

附:真的,我想要的是一些简单的东西,比如

MemoryStream compressed = GZipStream(uncompressed, Compress)
MemoryStream upcompressed = GZipStream(compressed, Decompress)

【问题讨论】:

  • 写入压缩,读取解压缩。
  • 在这两种情况下,GZipStream 的底层流都包含压缩数据。
  • 您的第一种方法应该有效。您确定您使用的字节数组是原始压缩的吗?您不能只是将压缩的字节数组放在一起并期望它被反编译。
  • 如果没有一个好的minimal reproducible example,就不可能确定你做错了什么。 “如何”的简短版本是:从您的 byte[] 创建 MemoryStream,将该流传递给 GZipStream,然后从 GZipStream读取
  • 好,如果你的顺序正确,你的第一种方法应该不会有问题。

标签: c# gzipstream


【解决方案1】:

此代码示例有效。第一部分只是得到一个压缩的字节数组。第二部分演示了如何在代码中创建压缩流,可以多次写入。但是位置必须设置为0。

byte[] compressed;
string output;

using (var outStream = new MemoryStream()) {
    using (var tinyStream = new GZipStream(outStream, CompressionMode.Compress))
    using (var mStream = new MemoryStream(Encoding.UTF8.GetBytes("This is a test"))) {
        mStream.CopyTo(tinyStream);
    }
    compressed = outStream.ToArray();
}

using (var compressedStream = new MemoryStream()) {
    // can do multiple writes here to create the compressed stream
    compressedStream.Write(compressed, 0, compressed.Length);
    compressedStream.Flush();
    compressedStream.Position = 0;
    using (var unzippedStream = new GZipStream(compressedStream, CompressionMode.Decompress))
    using (var uncompressedStream = new MemoryStream()) {
        unzippedStream.CopyTo(uncompressedStream);
        output = Encoding.UTF8.GetString(uncompressedStream.ToArray());
    }
}

Console.WriteLine(output);

【讨论】:

    猜你喜欢
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    相关资源
    最近更新 更多