网上找了一个关于序列化和压缩相关的方法,记录下来,以便日后用!
#region 可序列化对象到byte数组的相互转换/// <summary>/// 将可序列化对象转成Byte数组/// </summary>/// <param name="o">对象</param>/// <returns>返回相关数组</returns>public static byte[] ObjectToByteArray(object o){MemoryStream ms = new MemoryStream();BinaryFormatter bf = new BinaryFormatter();bf.Serialize(ms, o);ms.Close();return ms.ToArray();}/// <summary>/// 将可序列化对象转成的byte数组还原为对象/// </summary>/// <param name="b">byte数组</param>/// <returns>相关对象</returns>public static object ByteArrayToObject(byte[] b){MemoryStream ms = new MemoryStream(b, 0, b.Length);BinaryFormatter bf = new BinaryFormatter();return bf.Deserialize(ms);}#endregion#region 采用.net系统自带Gzip压缩类进行流压缩/// <summary>/// 压缩数据/// </summary>/// <param name="data"></param>/// <returns></returns>public static byte[] Compress(byte[] data){byte[] bData;MemoryStream ms = new MemoryStream();GZipStream stream = new GZipStream(ms, CompressionMode.Compress, true);stream.Write(data, 0, data.Length);stream.Close();stream.Dispose();//必须把stream流关闭才能返回ms流数据,不然数据会不完整//并且解压缩方法stream.Read(buffer, 0, buffer.Length)时会返回0bData = ms.ToArray();ms.Close();ms.Dispose();return bData;}/// <summary>/// 解压数据/// </summary>/// <param name="data"></param>/// <returns></returns>public static byte[] Decompress(byte[] data){byte[] bData;MemoryStream ms = new MemoryStream();ms.Write(data, 0, data.Length);ms.Position = 0;GZipStream stream = new GZipStream(ms, CompressionMode.Decompress, true);byte[] buffer = new byte[1024];MemoryStream temp = new MemoryStream();int read = stream.Read(buffer, 0, buffer.Length);while (read > 0){temp.Write(buffer, 0, read);read = stream.Read(buffer, 0, buffer.Length);}//必须把stream流关闭才能返回ms流数据,不然数据会不完整stream.Close();stream.Dispose();ms.Close();ms.Dispose();bData = temp.ToArray();temp.Close();temp.Dispose();return bData;}#endregion