BinaryFormatter是否应用任何压缩?

xyz*_*xyz 7 .net c# compression serialization binaryformatter

当.NET BinaryFormatter用于序列化对象图时,是否应用了任何类型的压缩?

我在上下文中询问是否应该担心具有许多重复字符串和整数的对象图.

编辑 - 保持,如果在.NET中实例化字符串,则无需担心重复的字符串,对吧?

And*_*are 10

不,它不提供任何压缩,但您可以使用GZipStream类型自己压缩输出.

编辑: Mehrdad在回答如何使用gzip压缩.net对象实例时有一个很好的例子.

编辑2:字符串可以被实习但这并不意味着每个字符串被实习.我不会做出对CLR如何或为何决定实习生字符串,因为这会改变(并改变)因版本的任何假设.


Dan*_*dor 5

不,它没有,但......

我今天刚刚为我的应用添加了GZipStream支持,所以我可以在这里分享一些代码;

连载:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

反序列化:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:如果您使用CryptoStream,以这种方式链接(取消)压缩和(解密)加密是很重要的,因为在加密会从您的数据中产生噪声之前,您将希望丢失熵.