如何在 C# 中用 SharpZipLib 進行 ZIP 壓縮與解壓)

來源:互聯網
上載者:User
轉自:http://www.cftea.com/c/2008/04/A1FQ34RYSYNLFT47.asp

SharpZipLib 是一個免費的組件,可以利用它對 ZIP 等多種格式進行壓縮與解壓。

  • 本地下載 SharpZipLib 0.85.4;
  • 本地下載 SharpZipLib 0.85.4 源檔案與樣本;
  • 本地下載 SharpZipLib 0.85.4 協助。

或者您也可以到官方網站下載最新版本:http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx

非常幸運的是,在這個版本中提供了 FastZip 類,可以非常方便地實現壓縮與解壓。

ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
zip.CreateZip("C:\\foo.zip", "C:\\待壓縮的檔案夾", true, ""); //第三個參數表示是否壓縮子檔案夾
zip.ExtractZip("C:\\foo.zip", "C:\\壓縮後存放的檔案夾", "");

如果我們只想壓縮目錄中的一個或部分檔案,或者我們只想解壓檔案中的一個或部分檔案,怎麼辦呢?那就得把最後一個參數用上,它是字串類型的Regex,比如只壓縮 ini 檔案用:"^.*(.ini)$"。關於Regex更多內容,請參見:Regex簡介(4)。

另外,我們還提供了一個用 ZipInputStream 進行解壓的樣本,樣本中壓縮檔是一個僅包含一個 txt 檔案的 zip 檔案,僅作拋磚引玉。

using ICSharpCode.SharpZipLib.Zip;
using System.IO;

//……

ZipInputStream zipStream = new ZipInputStream(File.Open("C:\\foo.zip", FileMode.Open));

ZipEntry entry = zipStream.GetNextEntry();
while (entry != null)
{
if (!entry.IsFile)
{
continue;
}

FileStream writer = File.Create("C:\\foo.txt"); //解壓後的檔案

int bufferSize = 2048; //緩衝區大小
int readCount = 0; //讀入緩衝區的實際位元組
byte[] buffer = new byte[bufferSize];
readCount = zipStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
writer.Write(buffer, 0, readCount);
readCount = zipStream.Read(buffer, 0, bufferSize);
}

writer.Close();
writer.Dispose();

entry = zipStream.GetNextEntry();
}

zipStream.Close();
zipStream.Dispose();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.