62 lines
2.1 KiB
C#
62 lines
2.1 KiB
C#
using System.IO;
|
|
using System.IO.Compression;
|
|
|
|
namespace AllBase
|
|
{
|
|
public static class ZipHelper
|
|
{
|
|
/// <summary>
|
|
/// GZip压缩
|
|
/// </summary>
|
|
/// <param name="rawData"></param>
|
|
/// <returns></returns>
|
|
public static byte[] Compress(byte[] rawData)
|
|
{
|
|
if (rawData == null || rawData.Length < 1000)
|
|
return rawData;
|
|
MemoryStream ms = new MemoryStream();
|
|
GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true);
|
|
compressedzipStream.Write(rawData, 0, rawData.Length);
|
|
compressedzipStream.Close();
|
|
return ms.ToArray();
|
|
}
|
|
|
|
/// <summary>
|
|
/// ZIP解压
|
|
/// </summary>
|
|
/// <param name="zippedData"></param>
|
|
/// <returns></returns>
|
|
public static byte[] Decompress(byte[] zippedData)
|
|
{
|
|
if (zippedData == null || zippedData.Length == 0)
|
|
return null;
|
|
if (zippedData.Length < 100)
|
|
return zippedData;
|
|
if (zippedData[2] != 0x8 || zippedData[3] != 0x0 || zippedData[4] != 0x0
|
|
|| zippedData[5] != 0x0 || zippedData[6] != 0x0 || zippedData[7] != 0x0
|
|
|| zippedData[0] != 31 || zippedData[1] != 139)//软加速判断头尾是否正确
|
|
return zippedData;
|
|
try
|
|
{
|
|
MemoryStream ms = new MemoryStream(zippedData);
|
|
GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Decompress);
|
|
MemoryStream outBuffer = new MemoryStream();
|
|
byte[] block = new byte[1024];
|
|
while (true)
|
|
{
|
|
int bytesRead = compressedzipStream.Read(block, 0, block.Length);
|
|
if (bytesRead < 1)
|
|
break;
|
|
outBuffer.Write(block, 0, bytesRead);
|
|
}
|
|
compressedzipStream.Close();
|
|
return outBuffer.ToArray();
|
|
}
|
|
catch
|
|
{
|
|
}
|
|
return zippedData;
|
|
}
|
|
}
|
|
}
|