How to compress a .net object instance using gzip

前端 未结 4 1758
执笔经年
执笔经年 2021-02-10 11:49

I am wanting to compress results from QUERYS of the database before adding them to the cache.

I want to be able to compress any reference type.

I have a working

4条回答
  •  盖世英雄少女心
    2021-02-10 12:47

    I just added GZipStream support for my app today, so I can share some code here;

    Serialization:

    using (Stream s = File.Create(PathName))
    {
        RijndaelManaged rm = new RijndaelManaged();
        rm.Key = CryptoKey;
        rm.IV = CryptoIV;
        using (CryptoStream cs = new CryptoStream(s, rm.CreateEncryptor(), CryptoStreamMode.Write))
        {
            using (GZipStream gs = new GZipStream(cs, CompressionMode.Compress))
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(gs, _instance);
            }
        }
    }
    

    Deserialization:

    using (Stream s = File.OpenRead(PathName))
    {
        RijndaelManaged rm = new RijndaelManaged();
        rm.Key = CryptoKey;
        rm.IV = CryptoIV;
        using (CryptoStream cs = new CryptoStream(s, rm.CreateDecryptor(), CryptoStreamMode.Read))
        {
            using (GZipStream gs = new GZipStream(cs, CompressionMode.Decompress))
            {
                BinaryFormatter bf = new BinaryFormatter();
                _instance = (Storage)bf.Deserialize(gs);
            }
        }
    }
    

    NOTE: if you use CryptoStream, it is kinda important that you chain (un)zipping and (de)crypting right this way, because you'll want to lose your entropy BEFORE encryption creates noise from your data.

提交回复
热议问题