using System;
|
using System.Collections.Generic;
|
using System.Linq;
|
using System.Text;
|
using System.IO;
|
using System.IO.Compression;
|
using System.Runtime.InteropServices;
|
using System.Runtime.Serialization;
|
using System.Runtime.Serialization.Formatters.Binary;
|
|
|
namespace BatchService.Framework.Utility
|
{
|
public class ZIPHelper
|
{
|
/// <summary>
|
/// 将一个object对象序列化,返回一个byte[]
|
/// </summary>
|
/// <param name="obj">能序列化的对象</param>
|
/// <returns></returns>
|
public static byte[] ObjectToBytes(object obj)
|
{
|
using (MemoryStream ms = new MemoryStream())
|
{
|
IFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, obj); return ms.GetBuffer();
|
}
|
}
|
private static byte[] StreamToBytes(Stream stream)
|
{
|
byte[] bytes = new byte[stream.Length];
|
stream.Read(bytes, 0, bytes.Length);
|
// 设置当前流的位置为流的开始
|
stream.Seek(0, SeekOrigin.Begin);
|
return bytes;
|
}
|
/// <summary>
|
/// 将一个序列化后的byte[]数组还原
|
/// </summary>
|
/// <param name="Bytes"></param>
|
/// <returns></returns>
|
public static object BytesToObject(byte[] Bytes)
|
{
|
using (MemoryStream ms = new MemoryStream(Bytes))
|
{
|
IFormatter formatter = new BinaryFormatter(); return formatter.Deserialize(ms);
|
}
|
}
|
|
|
public static byte[] Compress(byte[] inBytes)
|
{
|
byte[] bb;
|
using (MemoryStream mStream = new MemoryStream(inBytes))
|
{
|
using (MemoryStream outStream = new System.IO.MemoryStream())
|
{
|
using (var tinyStream = new GZipStream(outStream, CompressionMode.Compress))
|
{
|
mStream.CopyTo(tinyStream);
|
}
|
bb = outStream.ToArray();
|
}
|
}
|
return bb;
|
}
|
|
|
|
public static byte[] Decompress(byte[] bytes)
|
{
|
try
|
{
|
byte[] output = new byte[1024 * 1024 * 10];
|
using (var inStream = new MemoryStream(bytes))
|
using (var bigStream = new GZipStream(inStream, CompressionMode.Decompress))
|
using (var bigStreamOut = new MemoryStream())
|
{
|
bigStream.CopyTo(bigStreamOut);
|
output = bigStreamOut.ToArray();
|
var output2 = Encoding.UTF8.GetString(bigStreamOut.ToArray());
|
}
|
return output;
|
}
|
catch (Exception e)
|
{
|
LogHelper.Error(e.Message);
|
return null;
|
}
|
|
}
|
}
|
|
}
|