Go homepage(回首页) Upload pictures (上传图片) Write articles (发文字帖)
The author:(作者)delvpublished in(发表于) 2014/1/10 6:28:11 ASP.NET技巧:用GZip压缩和解压_[Asp.Net教程]
.Net支持两种压缩格式:GZip和Deflate。我试了一下,压缩率和速度没区别。其中,GZip可以被WinRAR打开。
使用起来很简单,下面的程序将字符串压缩入文件:
using (DeflateStream gzip = new DeflateStream(fs, CompressionMode.Compress)) { byte[] buf = Encoding.UTF8.GetBytes(this.txbSource.Text); gzip.Write(buf, 0, buf.Length); gzip.Flush(); }
解压只需要这样:
gzip = new GZipStream(new MemoryStream(buf), CompressionMode.Decompress); using (StreamReader reader = new StreamReader(gzip)) { this.txbTarget.Text = reader.ReadToEnd(); }
如果从文件解压,只需要把MemoryStream换成一个FileStream就行了。当然,需要加:using System.IO.Compression;
来源:网络
赞