﻿# 介紹幾款好用的壓縮函示庫：SharpZipLib 與 DotNetZip

在專案中或多或少都有機會遇到需要處理壓縮檔的情況，而一般最常見的壓縮格式就是 [ZIP 格式](http://en.wikipedia.org/wiki/ZIP_\(file_format\))，雖然有人愛用 [RAR 格式](http://en.wikipedia.org/wiki/Rar)，但因為若要建立 RAR 壓縮檔時，只能用 [WinRAR](http://en.wikipedia.org/wiki/WinRAR) 軟體，而這是個需付費的商業軟體，所以我本身很不愛用，大多僅使用 [ZIP](http://en.wikipedia.org/wiki/ZIP_\(file_format\)) 或 [7-Zip](http://en.wikipedia.org/wiki/7-Zip) 等較為開放的壓縮格式。

今天我就來介紹兩款我曾經用過的壓縮函示庫：

1\. [**SharpZipLib - .NET Zip Library**](http://www.icsharpcode.net/OpenSource/SharpZipLib/)

[SharpZipLib](http://www.icsharpcode.net/OpenSource/SharpZipLib/) 是完全用 C# 撰寫並附有完整原始碼可供下載，此元件也已經問世一段時間了，我幾年前就用過了，支援多種壓縮格式，包括 Zip, GZip, BZip2 and Tar 等。

至於使用此元件的方式是採用 Stream 的方式開發，跟 [.NET BCL](http://en.wikipedia.org/wiki/Base_Class_Library) 內建的 [GZipStream](http://msdn.microsoft.com/zh-tw/library/system.io.compression.gzipstream.aspx) 用法差不多，差別在於 ZIP 格式可以壓縮「多個檔案」而已，若已經有使用過 [GZipStream](http://msdn.microsoft.com/zh-tw/library/system.io.compression.gzipstream.aspx) 的人要上手也不是什麼難事。

以下是我從下載的範例程式中擷取的程式碼片段，這段是用來建立一個 Zip 檔的範例：

```
string[] filenames = Directory.GetFiles(args[0]);
using (ZipOutputStream s = new ZipOutputStream(File.Create(args[1])))
{
    s.SetLevel(9); // 0 - store only to 9 - means best compression
    byte[] buffer = new byte[4096];
    foreach (string file in filenames)
    {
        ZipEntry entry = new ZipEntry(Path.GetFileName(file));
        entry.DateTime = DateTime.Now;
        s.PutNextEntry(entry);        
        using ( FileStream fs = File.OpenRead(file) ) {
            int sourceBytes;
            do {
                sourceBytes = fs.Read(buffer, 0, buffer.Length);
                s.Write(buffer, 0, sourceBytes);
            } while ( sourceBytes > 0 );
        }
    }    
    s.Finish();
    s.Close();
}
```

2\. [**DotNetZip - anage ZIP files from within .NET applications**](https://web.archive.org/web/20090106064435/http://code.msdn.microsoft.com:80/DotNetZip)

如果你單純的只想使用 Zip 壓縮、解壓縮的話，我個人是建議使用 [DotNetZip](https://web.archive.org/web/20090106064435/http://code.msdn.microsoft.com:80/DotNetZip) 即可，光看範例程式就知道他的精簡與直覺的使用方法：

**壓縮檔案**

```
using (ZipFile zip = new ZipFile("Archive.zip"))
{
    zip.AddFile("ReadMe.txt");
    zip.AddFile("7440-N49th.png");
    zip.AddFile("2005_Annual_Report.pdf");        
    zip.Save();
}
```

**壓縮檔案 ( 含密碼保護 )**

```
using (ZipFile zip = new ZipFile("Backup.zip"))
{
  zip.Password= "123456!";
  zip.AddFile("ReadMe.txt");
  zip.AddFile("7440-N49th.png");
  zip.AddFile("2005_Annual_Report.pdf");        
  zip.Save();
}
```

**壓縮檔案 ( 可根據不同檔案設定不同的解壓縮密碼 )**

```
using (ZipFile zip = new ZipFile("Backup.zip"))
{
  zip.AddFile("ReadMe.txt"); // no password for this entry

  zip.Password= "123456!";
  ZipEntry e = zip.AddFile("7440-N49th.png");
  e.Comment = "Map of the company headquarters."; 

  zip.Password= "!Secret1";
  zip.AddFile("2Q2008_Operations_Report.pdf");
  
  zip.Save();
}
```

**壓縮整個目錄 ( 還可對壓縮的項目設定註解 )**

```
using (ZipFile zip = new ZipFile(ZipFileToCreate))
{
  zip.AddDirectory(@"MyDocuments\ProjectX");
  zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G") ; 
  zip.Save();
}
```

**在 ASP.NET 頁面中實做下載壓縮檔功能 ( 直接將壓縮檔輸出到 [Response.OutputStream](http://msdn.microsoft.com/zh-tw/library/system.web.httpresponse.outputstream.aspx) 喔 )**

```
public void btnGo_Click (Object sender, EventArgs e)
{
  Response.Clear();
  String ReadmeText= "This is a zip file dynamically generated at " 
    + System.DateTime.Now.ToString("G");
  string filename = System.IO.Path.GetFileName(ListOfFiles.SelectedItem.Text) + ".zip";
  Response.ContentType = "application/zip";
  Response.AddHeader("content-disposition", "filename=" + filename);
  
  using (ZipFile zip = new ZipFile(Response.OutputStream)) {
    zip.AddFile(ListOfFiles.SelectedItem.Text, "files");
    zip.AddFileFromString("Readme.txt", "", ReadmeText);
    zip.Save();
  }
 
  Response.End();
}
```

還有一堆範例程式可以在[這裡](http://www.codeplex.com/DotNetZip/Wiki/View.aspx?title=Examples&referringTitle=Home)看到。不過光看到以上的範例就知道好用了吧！ ^\_^

\---

最後，還有一個鮮為人知的壓縮、解壓縮的類別庫潛藏在 [Visual J# Class Library](http://msdn.microsoft.com/en-us/library/aa988212\(VS.80\).aspx) 中，說也奇怪，這麼常用的功能盡然潛藏在一個這麼少人用的地方，若有興趣瞭解的人可以參考以下文章：

-   [Using the Zip Classes in the J# Class Libraries to Compress Files and Data with C#](http://msdn.microsoft.com/en-us/magazine/cc164129.aspx)
-   [Simple application to Zip and UnZip files in C# using J# libraries](http://www.c-sharpcorner.com/UploadFile/neo_matrix/SharpZip04242007001341AM/SharpZip.aspx)

**相關連結**

-   [SharpZipLib - .NET Zip Library](http://www.icsharpcode.net/OpenSource/SharpZipLib/)
-   [SharpZipLib - Frequently Asked Questions](http://wiki.sharpdevelop.net/Default.aspx?Page=SharpZipLib_FAQ)
-   [DotNetZip Library @ MSDN Code Gallery](https://web.archive.org/web/20090106064435/http://code.msdn.microsoft.com:80/DotNetZip)
-   [DotNetZip Library @ CodePlex](http://www.codeplex.com/DotNetZip)
-   [DotNetZip Library – C# Examples](http://www.codeplex.com/DotNetZip/Wiki/View.aspx?title=Examples&referringTitle=Home)
-   [Using the Zip Classes in the J# Class Libraries to Compress Files and Data with C#](http://msdn.microsoft.com/en-us/magazine/cc164129.aspx)
-   [Simple application to Zip and UnZip files in C# using J# libraries](http://www.c-sharpcorner.com/UploadFile/neo_matrix/SharpZip04242007001341AM/SharpZip.aspx)
-   [Visual J# Class Library](http://msdn.microsoft.com/en-us/library/aa988212\(VS.80\).aspx)
-   [ZIP (文件格式) - 維基百科](http://zh.wikipedia.org/w/index.php?title=ZIP_\(%E6%96%87%E4%BB%B6%E6%A0%BC%E5%BC%8F\)&variant=zh-tw)
-   [DEFLATE - 維基百科，自由的百科全書](http://zh.wikipedia.org/wiki/DEFLATE)
