首先,我注意到压缩对象需要更多字节,然后纯粹以二进制形式表示对象。(228 对 166)。
其次,我似乎无法解压缩它。
此外,由于我没有 .NET 框架的第 4 版,因此我无法使用出色的 CopyTo 功能。
最后一个 DeflateStream 使用块需要做什么?
MyClass MyObj = new MyClass();
MyObj.MyProp1 = true;
MyObj.MyProp2 = "Dee";
MyClass MyObAfterSerDeser = null;
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, MyObj);
byte[] prebytes = ms.ToArray(); // length 166.
ms.SetLength(0L);
using(MemoryStream tmpms = new MemoryStream())
{
using (DeflateStream dsc = new DeflateStream(tmpms, CompressionMode.Compress))
{
dsc.Write(prebytes, 0, prebytes.Length);
tmpms.WriteTo(ms); // unforunately though, just want the # of compressed bytes.
}
}
byte[] cbytes = ms.ToArray(); // length 228. Longer than uncompressed version!
ms.SetLength(0L);
using (MemoryStream tmpms = new MemoryStream())
{
tmpms.Write(cbytes, 0, cbytes.Length);
tmpms.Position = 0;
using (DeflateStream dsd = new DeflateStream(tmpms, CompressionMode.Decompress))
{
byte[] dbytes = new byte[cbytes.Length];
dsd.Read(dbytes, 0, dbytes.Length);
int offset = ReadAllBytesFromStream(dsd, dbytes); // written by Mr. Skeet.
// dsd.Write(dbytes, 0, cbytes.Length);
// dsd.Read(dbytes, 0, dbytes.Length);
ms.Write(dbytes, 0, offset);
}
}
MyObAfterSerDeser = (MyClass)bf.Deserialize(ms);
}