一、 IPWorks! Zip V8 .NET Edition
需要添加引用 nsoftware.IPWorksZip.dll
//数据压缩
public static byte[] CompressData(byte[] buffer)
{
try
{
Zipstream zipstream = new Zipstream();
buffer = zipstream.CompressData(buffer);
zipstream.Dispose();
return buffer;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
throw ex;
}
}
//数据解压
public static byte[] DeCompressData(byte[] buffer)
{
try
{
Zipstream zipstream = new Zipstream();
buffer = zipstream.DecompressData(buffer);
zipstream.Dispose();
return buffer;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
throw ex;
}
}
二、Microsoft基于 .NET Framework 2.0 及以上版本
添加System.IO.Compression的引用
#region 解压缩
public static byte[] CompressData(byte[] bytes)
{
using (MemoryStream ms = new MemoryStream())
{
GZipStream Compress = new GZipStream(ms, CompressionMode.Compress);
Compress.Write(bytes, 0, bytes.Length);
Compress.Close();
return ms.ToArray();
}
}
public static byte[] DeCompressData(Byte[] bytes)
{
using (MemoryStream tempMs = new MemoryStream())
{
using (MemoryStream ms = new MemoryStream(bytes))
{
GZipStream Decompress = new GZipStream(ms, CompressionMode.Decompress);
Decompress.CopyTo(tempMs);
Decompress.Close();
return tempMs.ToArray();
}
}
}
#endregion
三、
public static byte[] CompressData(byte[] bytesToCompress)
{
byte[] rebyte = null;
using (MemoryStream ms = new MemoryStream())
{
GZipOutputStream s = new GZipOutputStream(ms);
s.Write(bytesToCompress, 0, bytesToCompress.Length);
s.Finish();
s.Close();
rebyte = ms.ToArray();
}
return rebyte;
}
public static byte[] DeCompressData(Byte[] outputBytes)
{
int originalLen = outputBytes.Length;
int maxDecompressLen = 20 * originalLen;
if (maxDecompressLen < 100000)
{
maxDecompressLen = 100000;
}
if (maxDecompressLen > 8000000)
{
maxDecompressLen = 8000000;
}
byte[] decompressByteArr = new byte[maxDecompressLen];
int read = -1;
try
{
GZipInputStream s = new GZipInputStream(new MemoryStream(outputBytes));
MemoryStream outStream = new MemoryStream();
read = s.Read(decompressByteArr, 0, decompressByteArr.Length);
while
(read > 0)
{
outStream.Write(decompressByteArr, 0, read);
read = s.Read(decompressByteArr, 0, decompressByteArr.Length);
}
s.Close();
return outStream.ToArray();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}