压缩、系列化对象

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;
using System.Runtime.Serialization.Formatters.Binary;

namespace NetMethod
{
public class SerializerZip
{
public static byte[] Serialize(object obj)
{
byte[] buffer = Serializer.Serialize(obj);
using (MemoryStream stream = new MemoryStream())
{
using (GZipStream gzipStream = new GZipStream(stream, CompressionMode.Compress, true))
{
gzipStream.Write(buffer, 0, buffer.Length);
}
return stream.ToArray();
}
}

public static object DeSerialize(byte[] buffer, int len, int offset = 0)
{
object obj = null;
using (MemoryStream stream = new MemoryStream(buffer, offset,Math.Abs(len)))
{
stream.Position = 0;
using (GZipStream gzipStream = new GZipStream(stream, CompressionMode.Decompress))
{
byte[] tempbuffer = new byte[4096];
int tempoffset = 0;
using (MemoryStream ms = new MemoryStream())
{
while ((tempoffset = gzipStream.Read(tempbuffer, 0, tempbuffer.Length)) != 0)
{
ms.Write(tempbuffer, 0, tempoffset);
}
ms.Position = 0;
try
{
obj = (object)Serializer.DeSerialize(ms);
}
catch
{

}
}
}
}
return obj;
}
}

public static class Serializer
{
/// <summary>
/// 使用二进制序列化对象。
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static byte[] Serialize(object value)
{
if (value == null) return null;
using (MemoryStream stream = new MemoryStream())
{
new BinaryFormatter().Serialize(stream, value);
return stream.ToArray();
}
}

/// <summary>
/// 使用二进制反序列化对象。
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static object DeSerialize(Stream stream)
{
return new BinaryFormatter().Deserialize(stream);
}
}
}

原文地址:https://www.cnblogs.com/94cool/p/3198439.html