如何使用gzip压缩.net对象实例 [英] How to compress a .net object instance using gzip
问题描述
我想在将数据库的QUERYS的结果添加到缓存之前压缩它们。
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.
我有一个压缩字符串的工作版本。基于scott hanselman的博客的想法 http://shrinkster.com/173t
I have a working version of this for compressing strings.. the idea based on scott hanselman 's blog post http://shrinkster.com/173t
压缩.net对象的任何想法?
any ideas for compressing a .net object?
我知道它将是只读缓存,因为缓存中的对象只是字节数组。
I know that it will be a read only cache since the objects in the cache will just be byte arrays..
推荐答案
这不适用于任何引用类型。这将适用于可序列化类型。将 BinaryFormatter
链接到通过管道传输到文件的压缩流:
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();
}
您可以使用 MemoryStream
将内容保存在内存中,而不是写入文件。我怀疑这是真正的缓存的有效解决方案,但是。
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.
这篇关于如何使用gzip压缩.net对象实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!