.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();
}
{
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();
}
using (StreamReader reader = new StreamReader(gzip))
{
this .txbTarget.Text = reader.ReadToEnd();
}
如果从文件解压,只需要把MemoryStream换成一个FileStream就行了。
当然,需要加:using System.IO.Compression;