首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

.NET 內建庫生成 ZIP 檔案的完整實作指南

     編輯:ASP.NET 基礎

.NET Framework 內建的 System.IO.Packaging 命名空間(位於 WindowsBase.dll 中)提供了無需第三方庫即可建立 ZIP 檔案的功能。本文透過一個完整的 Console 應用程式範例,示範如何遞迴壓縮整個資料夾結構。

前置準備

  1. 建立一個包含子目錄與檔案的測試資料夾。
  2. 建立 Console 專案,加入 WindowsBase 參考。
  3. 在程式碼中引用 System.IO.Packaging 命名空間。

核心類別實作:ZipManager

1. 建構函數與欄位

public class ZipManager
{
    private readonly string _sourcePath;

    public ZipManager(string sourcePath)
    {
        _sourcePath = sourcePath;
    }
}

2. 主要壓縮方法 ZipFolder

建立 Package 實例(以 FileMode.Create 開啟),並呼叫遞迴方法處理目錄:

public void ZipFolder(string zipFilePath)
{
    using (Package package = Package.Open(zipFilePath, FileMode.Create))
    {
        ZipDirectory(package, _sourcePath, "");
    }
}

3. 遞迴遍歷目錄:ZipDirectory

關鍵在於計算「相對路徑」並統一使用正斜線(/),符合 Package Part URI 規格:

private void ZipDirectory(Package package, string folderPath, string relativePath)
{
    foreach (string file in Directory.GetFiles(folderPath))
    {
        string fileRelativePath = relativePath + Path.GetFileName(file).Replace('\\', '/');
        Uri partUri = new Uri(fileRelativePath, UriKind.Relative);
        PackagePart part = package.CreatePart(partUri, "", CompressionOption.Normal);
        using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
        using (Stream dest = part.GetStream())
        {
            CopyStream(fs, dest);
        }
    }

    foreach (string dir in Directory.GetDirectories(folderPath))
    {
        string dirName = Path.GetFileName(dir);
        ZipDirectory(package, dir, relativePath + dirName + "/");
    }
}

4. 資料流複製輔助方法

private void CopyStream(Stream source, Stream destination)
{
    byte[] buffer = new byte[4096];
    int bytesRead;
    while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
    {
        destination.Write(buffer, 0, bytesRead);
    }
}

呼叫範例

class Program
{
    static void Main(string[] args)
    {
        string source = @"D:\TestFolder";
        string zipFile = @"D:\Output.zip";
        ZipManager zm = new ZipManager(source);
        zm.ZipFolder(zipFile);
        Console.WriteLine("壓縮完成!");
    }
}

進階擴充建議

  • 使用 PackUriHelper 簡化 URI 建立。
  • 依需求調整 CompressionOption(Normal/Fast/Maximum)。
  • 參考 MSDN 文件深入了解 System.IO.Packaging 的完整功能。

測試資料夾結構

資料夾內容

專案結構

加入 WindowsBase 參考

引用命名空間

建構函數

ZipFolder 方法

ZipDirectory 遞迴

建立 PackagePart

CopyStream 方法

呼叫 ZipManager

生成的 ZIP 檔案

ZIP 內容預覽

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved