序列化:
public static byte[] Serialize<T>(T msg)
{
using (MemoryStream ms=new MemoryStream())
{
try
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, msg);
ms.Seek(0, SeekOrigin.Begin);
return ms.ToArray();
}
catch (SerializationException e)
{
throw;
}
}
}
反序列化:
public static T DeSerialize<T>(byte[] bytes)
{
using (MemoryStream ms = new MemoryStream(bytes))
{
try
{
BinaryFormatter bf = new BinaryFormatter();
T msg = (T)bf.Deserialize(ms);
return msg;
}
catch (SerializationException e)
{
throw;
}
}
}
压缩:
public static byte[] Compress(byte[] input) {
using(MemoryStream outMS = new MemoryStream()) {
using(GZipStream gzs = new GZipStream(outMS, CompressionMode.Compress, true)) {
gzs.Write(input, 0, input.Length);
gzs.Close();
return outMS.ToArray();
}
}
}
解压:
public static byte[] DeCompress(byte[] input) {
using(MemoryStream inputMS = new MemoryStream(input)) {
using(MemoryStream outMs = new MemoryStream()) {
using(GZipStream gzs = new GZipStream(inputMS, CompressionMode.Decompress)) {
byte[] bytes = new byte[1024];
int len = 0;
while((len = gzs.Read(bytes, 0, bytes.Length)) > 0) {
outMs.Write(bytes, 0, len);
}
gzs.Close();
return outMs.ToArray();
}
}
}
}