【问题标题】:GZIPStream Compression Always Returns 10 BytesGZIPStream 压缩总是返回 10 字节
【发布时间】:2016-10-20 08:24:14
【问题描述】:

我正在尝试压缩我的 UWP 应用程序中的一些文本。我创建了这个方法以便以后更容易:

public static byte[] Compress(this string s)
{
    var b = Encoding.UTF8.GetBytes(s);
    using (MemoryStream ms = new MemoryStream())
    using (GZipStream zipStream = new GZipStream(ms, CompressionMode.Compress))
    {
        zipStream.Write(b, 0, b.Length);
        zipStream.Flush(); //Doesn't seem like Close() is available in UWP, so I changed it to Flush(). Is this the problem?
        return ms.ToArray();
    }
}

但不幸的是,无论输入文本是什么,它总是返回 10 个字节。是不是因为我没有在GZipStream上使用.Close()

【问题讨论】:

    标签: c# compression uwp gzipstream


    【解决方案1】:

    您过早地返回字节数据。 Close() 方法被 Dispose() 方法取代。因此,GZIP 流将仅在您离开 using(GZipStream) {}之后被释放时写入。

    public static byte[] Compress(string s)
    {
        var b = Encoding.UTF8.GetBytes(s);
        var ms = new MemoryStream();
        using (GZipStream zipStream = new GZipStream(ms, CompressionMode.Compress))
        {
            zipStream.Write(b, 0, b.Length);
            zipStream.Flush(); //Doesn't seem like Close() is available in UWP, so I changed it to Flush(). Is this the problem?
        }
    
        // we create the data array here once the GZIP stream has been disposed
        var data    = ms.ToArray();
        ms.Dispose();
        return data;
    }
    

    【讨论】:

    • 是的,这就像一个魅力!我之前尝试过使用.Dispose(),但我没有在 using() 块之外使用它,而是在返回数据之前调用它,这导致ms 也被处理掉了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    相关资源
    最近更新 更多