萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 目錄/檔案壓縮下載:SharpZipLib 實作完整指南

前置準備

  1. NuGet 安裝:Install-Package SharpZipLib
  2. 引用命名空間:
    using System.IO;
    using ICSharpCode.SharpZipLib.Zip;
    using ICSharpCode.SharpZipLib.Checksums;
    

核心功能:資料夾遞迴壓縮並直接下載 (MemoryStream 零臨時檔)

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);
    }
}

ASP.NET WebForms 頁面整合

<%@ 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 方法放在這裡
}

ASP.NET Core / MVC Controller 版本

[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 特有)

常見問題排查

  • 下載檔案損壞/無法解壓:確認 `zipStream.Finish()` 被呼叫、無額外輸出 (Response.Write 等)、`Response.SuppressContent=true`
  • 中文檔名亂碼:SharpZipLib 內部使用 UTF-8,確保 `entryName` 為正確字串,現代解壓工具 (WinRAR、7-Zip、Windows 原生) 均支援 UTF-8
  • 記憶體爆炸:使用 `Response.BufferOutput=false` + 串流寫入 + 4KB 緩衝區,不載入整個檔案到記憶體
  • ThreadAbortException:用 `CompleteRequest()` 替代 `Response.End()`
  • 權限不足:應用程式池身分需有來源資料夾讀取權限

替代方案:System.IO.Compression (內建、無第三方依賴)

// .NET Core / .NET 5+ 僅需 using System.IO.Compression;
using (var zip = ZipFile.OpenRead(zipPath)) { ... } // 讀取
ZipFile.CreateFromDirectory(sourceDir, zipPath); // 簡單壓縮整個目錄 (但無串流下載、無密碼、無細粒度控制)

SharpZipLib 適合需要**串流下載、密碼保護、細粒度控制、.NET Framework 相容**的場景。純 .NET Core 簡單壓縮用內建即可。

copyright © 萬盛學電腦網 all rights reserved