Install-Package SharpZipLibusing System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
public void DownloadFolderAsZip(string folderPath, string zipFileName)
{
// 1. 設定回應標頭
Response.Clear();
Response.ContentType = "application/zip";
Response.AddHeader("Content-Disposition", $"attachment; filename=\"{HttpUtility.UrlEncode(zipFileName, System.Text.Encoding.UTF8)}.zip\"");
Response.BufferOutput = false; // 串流輸出,不佔用大量記憶體
// 2. 建立 ZipOutputStream 直接寫入 Response.OutputStream
using (var zipStream = new ZipOutputStream(Response.OutputStream))
{
zipStream.SetLevel(6); // 壓縮等級 0-9 (6 平衡速度/壓縮比)
// zipStream.Password = "optional_password"; // 可選加密
// 3. 遞迴加入檔案
AddDirectoryToZip(zipStream, folderPath, "");
// 4. 完成並刷新
zipStream.Finish(); // 必須呼叫,寫入中央目錄
zipStream.Close();
}
Response.Flush();
Response.SuppressContent = true; // 防止頁面生命週期追加內容
HttpContext.Current.ApplicationInstance.CompleteRequest(); // 替代 Response.End() 避免 ThreadAbortException
}
void AddDirectoryToZip(ZipOutputStream zipStream, string sourceDir, string relativePath)
{
// 目錄項目 (隱式由檔案項目建立,或顯式建立)
// foreach (string dir in Directory.GetDirectories(sourceDir)) { ... }
foreach (string filePath in Directory.GetFiles(sourceDir))
{
string fileName = Path.GetFileName(filePath);
string entryName = Path.Combine(relativePath, fileName).Replace("\\", "/"); // ZIP 內部路徑用正斜線
// 建立 ZipEntry
var entry = new ZipEntry(entryName)
{
DateTime = File.GetLastWriteTime(filePath),
Size = new FileInfo(filePath).Length
};
zipStream.PutNextEntry(entry);
// 串流複製檔案內容 (避免大檔案載入記憶體)
byte[] buffer = new byte[4096];
using (FileStream fs = File.OpenRead(filePath))
{
int count;
while ((count = fs.Read(buffer, 0, buffer.Length)) > 0)
{
zipStream.Write(buffer, 0, count);
}
}
}
// 遞迴子目錄
foreach (string dirPath in Directory.GetDirectories(sourceDir))
{
string dirName = Path.GetFileName(dirPath);
string newRelativePath = Path.Combine(relativePath, dirName).Replace("\\", "/");
AddDirectoryToZip(zipStream, dirPath, newRelativePath);
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DownloadZip.aspx.cs" Inherits="DownloadZip" %>
<asp:Button ID="btnDownload" Text="下載整個專案資料夾" OnClick="btnDownload_Click" runat="server" />
public partial class DownloadZip : System.Web.UI.Page
{
protected void btnDownload_Click(object sender, EventArgs e)
{
string userFolder = @"D:\Projects\MyProject"; // 實際路徑
string zipName = "MyProject_Backup_" + DateTime.Now.ToString("yyyyMMdd_HHmmss");
DownloadFolderAsZip(userFolder, zipName);
}
// 將上方 DownloadFolderAsZip、AddDirectoryToZip 方法放在這裡
}
[HttpGet("download-folder/{*folderPath}")]
public async Task DownloadFolder(string folderPath)
{
string fullPath = Path.Combine(_env.ContentRootPath, "UserData", folderPath);
if (!Directory.Exists(fullPath)) return NotFound();
string zipName = $"{Path.GetFileName(fullPath)}_{DateTime.Now:yyyyMMdd_HHmmss}.zip";
// 使用 PushStreamResult 串流輸出
return new PushStreamResult(async (outputStream, _, _) =>
{
using (var zipStream = new ZipOutputStream(outputStream))
{
zipStream.SetLevel(6);
AddDirectoryToZip(zipStream, fullPath, "");
zipStream.Finish();
}
await outputStream.FlushAsync();
}, "application/zip", (long?)null)
{ FileDownloadName = zipName };
}
| 功能 | 實作要點 |
|---|---|
| 密碼保護 | zipStream.Password = "pwd"; entry.AESKeySize = 256; (需 SharpZipLib 1.3+) |
| 排除特定檔案/目錄 | 在 AddDirectoryToZip 中過濾 .git、bin、obj、*.log、*.tmp |
| 大檔案分卷 | SharpZipLib 不直接支援分卷,需自行分割輸出流或使用其他庫 |
| 進度回報 | 計算總大小,在寫入迴圈中更新 Session/快取,前端 AJAX 輪詢 |
| 保留檔案權限/屬性 | ZipEntry.ExternalFileAttributes = (int)File.GetAttributes(filePath) << 16 (Windows 特有) |
// .NET Core / .NET 5+ 僅需 using System.IO.Compression;
using (var zip = ZipFile.OpenRead(zipPath)) { ... } // 讀取
ZipFile.CreateFromDirectory(sourceDir, zipPath); // 簡單壓縮整個目錄 (但無串流下載、無密碼、無細粒度控制)
SharpZipLib 適合需要**串流下載、密碼保護、細粒度控制、.NET Framework 相容**的場景。純 .NET Core 簡單壓縮用內建即可。