close
1.前言:
DotNetZip為一個開放式源碼軟體元件,可整合到.NET開發專案中,是一個容易操作使用的檔案壓縮/解壓縮元件。
2.說明:
DotNetZip的最新軟體可由下列網址下載:
http://dotnetzip.codeplex.com/
本範例使用的版本為v1.9.1.8
解壓縮軟體後,將\DotNetZipLib-DevKit-v1.9\zip-v1.9\Release\Ionic.Zlib.dll的DLL檔複製到自己專案下的bin目錄
加入參考: Ionic.Zlib.dll
加入命名空間:
using Ionic.Zlib;
程式碼:
private void btZip_Click(object sender, EventArgs e) { string path = @"d:\tmp\test";//要壓縮檔案的目錄路徑 ZipFiles(path, string.Empty, string.Empty); } private void btUnzip_Click(object sender, EventArgs e) { string path = @"d:\tmp\test1\test.zip";//壓縮檔案路徑 UnZipFiles(path, string.Empty); } //讀取目錄下所有檔案 private static ArrayList GetFiles(string path) { ArrayList files = new ArrayList(); if (Directory.Exists(path)) { files.AddRange(Directory.GetFiles(path)); } return files; } //建立目錄 private static void CreateDirectory(string path) { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } //壓縮檔案 //path: 壓縮檔案路徑 //password: 密碼 //comment: 註解 private void ZipFiles(string path, string password, string comment) { string zipPath = path + @"\" + Path.GetFileName(path) + ".zip"; ZipFile zip = new ZipFile(); if (password != null && password != string.Empty) zip.Password = password; if (comment != null && comment != "") zip.Comment = comment; ArrayList files = GetFiles(path); foreach (string f in files) { zip.AddFile(f, string.Empty);//第二個參數設為空值表示壓縮檔案時不將檔案路徑加入 } zip.Save(zipPath); } //解壓縮檔案 //path: 解壓縮檔案目錄路徑 //password: 密碼 private void UnZipFiles(string path, string password) { ZipFile unzip = ZipFile.Read(path); if (password != null && password != string.Empty) unzip.Password = password; string unZipPath = path.Replace(".zip", ""); foreach (ZipEntry e in unzip) { e.Extract(unZipPath, ExtractExistingFileAction.OverwriteSilently); } }
文章標籤
全站熱搜