#region 【Compress】方法:压缩数据
public static byte[] Compress(object obj)
{
MemoryStream mes = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(mes, obj);
byte[] unCmpData = mes.ToArray();
mes.Close();
mes.Dispose();
MemoryStream ms = new MemoryStream();
GZipStream gzs = new GZipStream(ms, CompressionMode.Compress, true);
gzs.Write(unCmpData, 0, unCmpData.Length);
gzs.Close();
gzs.Dispose();
byte[] cmpData = ms.ToArray();
ms.Close();
ms.Dispose();
return cmpData;
}
#endregion
#region 【Decompress】方法:解压数据
public static object Decompress(byte[] cmpData)
{
MemoryStream ms1 = new MemoryStream();
ms1.Write(cmpData, 0, cmpData.Length);
ms1.Position = 0;
GZipStream gzs = new GZipStream(ms1, CompressionMode.Decompress, true);
byte[] buffer = new byte[1024];
MemoryStream ms2 = new MemoryStream();
int length = gzs.Read(buffer, 0, buffer.Length);
while (length > 0)
{
ms2.Write(buffer, 0, length);
length = gzs.Read(buffer, 0, buffer.Length);
}
gzs.Close();
gzs.Dispose();
ms1.Close();
ms1.Dispose();
byte[] Data = ms2.ToArray();
ms2.Close();
ms2.Dispose();
MemoryStream ms = new MemoryStream(Data, 0, Data.Length);
BinaryFormatter bf = new BinaryFormatter();
return bf.Deserialize(ms);
}
#endregion
直接复制后调用即可~