本文介绍如何将一个对象(任何类型)压缩,并序列化为二进制。通过该种方式处理后,可以大幅减小数据占用空间。如果再将该二进制数转化为Base64String,就可以保存到磁盘,从而节省空间。
/// <summary> /// 将指定对象序列化为二进制。 /// </summary> /// <param name="obj">要序列化的对象。</param> /// <param name="iscompress">是否压缩。</param> public byte[] SerializeToBytes(object obj, bool iscompress = true) { if ("DataTable" == obj.GetType().Name) ((System.Data.DataTable)obj).RemotingFormat = System.Data.SerializationFormat.Binary; using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { ms.Position = 0; System.Runtime.Serialization.IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); if (iscompress) { using (System.IO.Compression.DeflateStream ds = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress)) bf.Serialize(ds, obj); } else { bf.Serialize(ms, obj); } return ms.ToArray(); } }