110 lines
3.5 KiB
C#
110 lines
3.5 KiB
C#
using System;
|
||
using System.IO;
|
||
using System.IO.Compression;
|
||
using System.Runtime.Serialization.Formatters.Binary;
|
||
|
||
namespace DeviceRepair.Utils
|
||
{
|
||
/// <summary>
|
||
/// 数据 GZip压缩
|
||
/// </summary>
|
||
public static class CompressionHelper
|
||
{
|
||
#region 对象转byte[]
|
||
/// <summary>
|
||
/// 转数据集并压缩
|
||
/// </summary>
|
||
/// <param name="obj"></param>
|
||
/// <returns></returns>
|
||
public static byte[] ToArrayAndCompress(this object obj)
|
||
{
|
||
if (obj == null)
|
||
return null;
|
||
|
||
byte[] bytes;
|
||
BinaryFormatter formatter = new BinaryFormatter();
|
||
using (MemoryStream memoryStream = new MemoryStream())
|
||
{
|
||
formatter.Serialize(memoryStream, obj);
|
||
bytes = memoryStream.ToArray();
|
||
}
|
||
return Compress(bytes);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解压缩并转化到对象
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="bytes"></param>
|
||
/// <returns></returns>
|
||
public static T DecompressAndSerializeObject<T>(this byte[] bytes) where T : class
|
||
{
|
||
byte[] debyte = Decompress(bytes);
|
||
BinaryFormatter formatter = new BinaryFormatter();
|
||
using (MemoryStream stream = new MemoryStream(debyte))
|
||
{
|
||
object obj = formatter.Deserialize(stream);
|
||
return (T)obj;
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
/// <summary>
|
||
/// 压缩
|
||
/// </summary>
|
||
/// <param name="data"></param>
|
||
/// <returns></returns>
|
||
public static byte[] Compress(this byte[] data)
|
||
{
|
||
using (var compressedStream = new MemoryStream())
|
||
{
|
||
using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
|
||
{
|
||
zipStream.Write(data, 0, data.Length);
|
||
zipStream.Close();
|
||
return compressedStream.ToArray();
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解压
|
||
/// </summary>
|
||
/// <param name="data"></param>
|
||
/// <returns></returns>
|
||
public static byte[] Decompress(this byte[] data)
|
||
{
|
||
using (var compressedStream = new MemoryStream(data))
|
||
{
|
||
using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
|
||
{
|
||
using (var resultStream = new MemoryStream())
|
||
{
|
||
zipStream.CopyTo(resultStream);
|
||
return resultStream.ToArray();
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 将传入字符串以GZip算法压缩后,返回Base64编码字符
|
||
/// </summary>
|
||
/// <param name="rawString">需要压缩的字符串</param>
|
||
/// <returns>压缩后的Base64编码的字符串</returns>
|
||
public static string GZipCompressString(string rawString)
|
||
{
|
||
if (string.IsNullOrEmpty(rawString) || rawString.Length == 0)
|
||
{
|
||
return "";
|
||
}
|
||
else
|
||
{
|
||
byte[] rawData = System.Text.Encoding.UTF8.GetBytes(rawString.ToString());
|
||
byte[] zippedData = Compress(rawData);
|
||
return (string)(Convert.ToBase64String(zippedData));
|
||
}
|
||
}
|
||
}
|
||
}
|