1. 程式人生 > >用GZip壓縮和解壓(.Net)

用GZip壓縮和解壓(.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;