创建如下类,目的是方便使用GZipStream类:
public class GZip
{
public static byte[] Compress(byte[] data)
{
MemoryStream stream = new MemoryStream();
GZipStream gZipStream = new GZipStream(stream, CompressionMode.Compress);
gZipStream.Write(data, 0, data.Length);
gZipStream.Close();
return stream.ToArray();
}
public static byte[] Decompress(byte[] data)
{
MemoryStream stream = new MemoryStream();
GZipStream gZipStream = new GZipStream(new MemoryStream(data), CompressionMode.Decompress);
byte[] bytes = new byte[40960];
int n;
while ((n = gZipStream.Read(bytes, 0, bytes.Length)) != 0)
{
stream.Write(bytes, 0, n);
}
gZipStream.Close();
return stream.ToArray();
}
}
用Compress进行压缩,用Decompress进行解压缩。该类需要有如下引用:
using System.IO;
using System.IO.Compression;
使用方法:
byte[] byteString=UnicodeEncoding.ASCII.GetBytes("abcd123456789");
byte[] gzipString = GZip.Compress(byteString);
byteString = GZip.Decompress(gzipString);
MessageBox.Show(UnicodeEncoding.ASCII.GetString(byteString));
转自:http://stanfordxu.blog.163.com/blog/static/7089328620095223229977/