使用「ZipArchive 類別」撰寫檔案壓縮、解壓縮範例

一、開發環境

  • 整合開發環境:Visual Studio 2019
  • 語言:C#
  • .net framework:4.6.2

二、組件

圖、組件 System.IO.Compression

三、專案結構介紹

圖、建置 Test/CompressionTest/Decompression 資料夾、在 Test/Compression 建置幾個測試檔案,在 Test/Decompression 建置 Test.zip 壓縮檔

四、解壓縮

  • 原始碼 C#
/// <summary>
/// 解壓縮
/// </summary>
private static void Decompression()
{
    var path = $"Test/Decompression/";

    using (var fs = new FileStream($"{path}\\Test.zip", FileMode.Open)) 
    {
        using (var archive = new ZipArchive(fs, ZipArchiveMode.Read, true))
        {
            foreach (var entry in archive.Entries)
            {
                if (File.Exists($"{path}\\{entry.Name}"))
                {
                    File.Delete($"{path}\\{entry.Name}");
                }
                entry.ExtractToFile($"{path}\\{entry.Name}");
            }
        }
    }
}

圖、執行結果



五、壓縮

  • 原始碼 C#
/// <summary>
/// 壓縮
/// </summary>
private static void Compression()
{
    var path = $"Test/Compression/";
    var files = Directory.GetFiles(path);

    using (var ms = new MemoryStream())
    {
        using (var za = new ZipArchive(ms, ZipArchiveMode.Create, true))
        {
            foreach (var f in files)
            {

                var fName = Path.GetFileName(f);
                var et = za.CreateEntry(fName);

                using (var zipStream = et.Open())
                {
                    var bts = File.ReadAllBytes(f);
                    zipStream.Write(bts, 0, bts.Length);
                }
            }
        }

        var data = ms.ToArray();
        File.WriteAllBytes($"{path}/text.zip", data);
    }
}

圖、執行結果



五、相關連結

  1. 使用「Visual Studio 2019」建置 主控台 Console 應用程式

六、參考

  1. ZipArchive 類別

留言

這個網誌中的熱門文章

使用「Visual Studio 2019」建置 Windows 服務

使用「LINE Messaging API」發送 line 訊息

讓 JavaScript 能在伺服器端執行的環境 「node.js」

如何傳送訊息至「Teams」的 Channel

好用的資料庫管理工具「SQL Server 資料庫專案」

使用「Visual Studio 2019」進行網站負載測試

使用「Visual Studio 2019」建置一個有 Mvc 和 Web Api 架構的網站

使用「SqlBulkCopy」進行大量資料寫入

「Katalon Recorder」簡化測試腳本撰寫的工具

asp.net 下的 JSON 套件最佳利器「Newtonsoft.Json」