How to compress a .net object instance using gzip

前端 未结 4 1759
执笔经年
执笔经年 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:50

    This won't work for any reference type. This will work for Serializable types. Hook up a BinaryFormatter to a compression stream which is piped to a file:

    var formatter = new BinaryFormatter();
    using (var outputFile = new FileStream("OutputFile", FileMode.CreateNew))
    using (var compressionStream = new GZipStream(
                             outputFile, CompressionMode.Compress)) {
       formatter.Serialize(compressionStream, objToSerialize);
       compressionStream.Flush();
    }
    

    You could use a MemoryStream to hold the contents in memory, rather than writing to a file. I doubt this is really an effective solution for a cache, however.

提交回复
热议问题