準備工作
- NuGet 安裝:
Install-Package SharpZipLib
- 引用命名空間:
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
using System.IO;
核心實作:遞迴壓縮目錄並串流輸出
public void DownloadFolderAsZip(string folderPath, string zipFileName) {
if (!Directory.Exists(folderPath)) { Response.StatusCode = 404; return; }
Response.Clear();
Response.BufferOutput = false; // 串流模式,不佔記憶體
Response.ContentType = "application/zip";
Response.AddHeader("Content-Disposition",
$"attachment; filename={HttpUtility.UrlEncode(zipFileName)}.zip");
using (var zipStream = new ZipOutputStream(Response.OutputStream)) {
zipStream.SetLevel(6); // 壓縮等級 0-9
AddDirectoryToZip(zipStream, folderPath, folderPath);
zipStream.Finish(); // 必須呼叫 Finish 寫入中央目錄
}
Response.End();
}
private void AddDirectoryToZip(ZipOutputStream zipStream, string basePath, string currentPath) {
string[] files = Directory.GetFiles(currentPath);
foreach (string file in files) {
string entryName = file.Substring(basePath.Length).TrimStart('\\', '/');
byte[] buffer = File.ReadAllBytes(file);
var entry = new ZipEntry(entryName) { DateTime = File.GetLastWriteTime(file), Size = buffer.Length };
zipStream.PutNextEntry(entry);
zipStream.Write(buffer, 0, buffer.Length);
}
string[] dirs = Directory.GetDirectories(currentPath);
foreach (string dir in dirs) {
AddDirectoryToZip(zipStream, basePath, dir);
}
}
按鈕事件呼叫
protected void btnDownload_Click(object sender, EventArgs e) {
string userPath = @"D:\Data\Export";
DownloadFolderAsZip(userPath, "ExportData");
}
關鍵優化點
- 串流輸出:`Response.BufferOutput = false` + 直接寫入 `Response.OutputStream`,避免大資料夾佔用記憶體
- 遞迴遍歷:保留相對路徑結構,解壓縮後目錄樹不變
- 檔案屬性保留:`DateTime`、`Size` 寫入 ZipEntry
- 壓縮等級:6 為平衡速度與比率,可調整
常見問題
- **中文檔名亂碼**:SharpZipLib 內部使用 UTF-8,現代瀏覽器皆支援;舊版 IE 需設 `zipStream.UseZip64 = UseZip64.Off`
- **超大資料夾逾時**:`Server.ScriptTimeout = 3600`;或改用背景作業生成暫存 ZIP,再提供下載連結
- **權限不足**:應用程式池身分需有來源資料夾讀取權限
替代方案
- .NET Core 3.0+ 內建 `System.IO.Compression.ZipFile.CreateFromDirectory`
- DotNetZip (Ionic.Zip) API 更直觀,但已停止維護