点网中的压缩对象 [英] Compressing Object in Dot Net

查看:77
本文介绍了点网中的压缩对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在点网中压缩对象以减小其大小,然后在客户端应用程序中对其进行解压缩。

I want to Compress an Object in dot net to reduce its size and then UnCompress it on in my client application.

感谢,
Mrinal Jaiswal

Thanks, Mrinal Jaiswal

推荐答案

我已经更新了代码,旧版本存在问题。

I have update the code there was a problem with older version.

这是一个序列化和压缩的功能,反之亦然。

Here is a function which serialize and compress and viceversa.

public static byte[] SerializeAndCompress(object obj) {

    using (MemoryStream ms = new MemoryStream()) {
        using (GZipStream zs = new GZipStream(ms, CompressionMode.Compress, true)) {
            BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(zs, obj);
        }
        return ms.ToArray();
    }
}
public static object DecompressAndDeserialze(byte[] data) {

    using (MemoryStream ms = new MemoryStream(data)) {
        using (GZipStream zs = new GZipStream(ms, CompressionMode.Decompress, true)) {
            BinaryFormatter bf = new BinaryFormatter();
            return bf.Deserialize(zs);
        }
    }
}

以下是如何使用它

    [Serializable]
    class MyClass
    {
        public string Name { get; set; }
    }

    static void Main(string[] args) {
        MyClass myClassInst = new MyClass();
        myClassInst.Name = "Some Data";

        byte[] data= SerializeAndCompress(myClassInst);
        MyClass desInst = (MyClass)DecompressAndDeserialze(data);

    }

但是有一个压力要压缩。请记住,上面的示例对象被序列化为153个字节,但是压缩版本为266个字节,原因是如果小对象的数据较少,则gzip标头信息和压缩标头至少将占用120个字节。因此,如果您的对象足够大而不是仅压缩300字节左右的大小,则无需压缩它们。您可以检查压缩率,看看是否需要压缩。

But there is a catch to compression. Remember the above example object is serialize to 153 bytes but the compress version is 266 bytes the reason is that if have small objects with less data then the gzip header information and compression header will at least take 120bytes. So if your object are big enough than compress them if they are just less 300 bytes or so its no need to compress them. You can check compression ratio and see if you object even require compression.

另一种建议是压缩大量数据总是比单个压缩对象更好。

Another suggestion try to compress bulk of data will always give better compression over individual compress objects.

这篇关于点网中的压缩对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆