dotnet C# 簡單的追加資料夾到 ZipArchive 壓縮檔案的方法

lindexi發表於2024-04-26

本文將告訴大家一個在 ZipArchive 裡追加資料夾,以及新增過濾檔案處理的壓縮檔案輔助方法

實現的方法的程式碼如下

    /// <summary>
    /// 追加資料夾到壓縮檔案裡面
    /// </summary>
    /// <param name="archive"></param>
    /// <param name="sourceDirectoryName"></param>
    /// <param name="zipRelativePath">在壓縮包裡面的相對路徑</param>
    /// <param name="compressionLevel"></param>
    /// <param name="fileCanAddedPredicate"></param>
    public static void AppendDirectoryToZipArchive(ZipArchive archive, string sourceDirectoryName, string zipRelativePath, CompressionLevel compressionLevel = CompressionLevel.Fastest, Predicate<string>? fileCanAddedPredicate = null)
    {
        var folders = new Stack<string>();

        folders.Push(sourceDirectoryName);

        while (folders.Count > 0)
        {
            var currentFolder = folders.Pop();

            foreach (var item in Directory.EnumerateFiles(currentFolder))
            {
                if (fileCanAddedPredicate != null && !fileCanAddedPredicate(item))
                {
                    continue;
                }

                archive.CreateEntryFromFile(item, Path.Join(zipRelativePath, Path.GetRelativePath(sourceDirectoryName, item)), compressionLevel);
            }

            foreach (var item in Directory.EnumerateDirectories(currentFolder))
            {
                folders.Push(item);
            }
        }
    }

演示的呼叫的程式碼如下

var zipFile = "1.zip";
using (var fileStream = new FileStream(zipFile, FileMode.Create, FileAccess.Write))
{
    using var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Create, leaveOpen: true/*自己釋放 FileStream 物件*/, Encoding.UTF8);
    Foo.AppendDirectoryToZipArchive(zipArchive, @"C:\lindexi\Library\", "Lib");
    Foo.AppendDirectoryToZipArchive(zipArchive, @"C:\lindexi\CA\", "Pem", fileCanAddedPredicate: filePath =>
    {
        var fileName = Path.GetFileName(filePath);
        return fileName != "foo.ignore.file";
    });
}

支援設定資料夾加入之後在安裝包的什麼相對路徑下,也支援過濾檔案

如果加入到安裝包的根路徑下,只需要讓 zipRelativePath 引數傳入空字串即可,如下面程式碼

    Foo.AppendDirectoryToZipArchive(zipArchive, @"C:\lindexi\Library\", "");

全部的程式碼如下

using System.IO.Compression;
using System.Text;

var zipFile = "1.zip";
using (var fileStream = new FileStream(zipFile, FileMode.Create, FileAccess.Write))
{
    using var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Create, leaveOpen: true/*自己釋放 FileStream 物件*/, Encoding.UTF8);
    Foo.AppendDirectoryToZipArchive(zipArchive, @"C:\lindexi\Library\", "Lib");
    Foo.AppendDirectoryToZipArchive(zipArchive, @"C:\lindexi\CA\", "Pem", fileCanAddedPredicate: filePath =>
    {
        var fileName = Path.GetFileName(filePath);
        return fileName != "foo.ignore.file";
    });
}


class Foo
{
    /// <summary>
    /// 追加資料夾到壓縮檔案裡面
    /// </summary>
    /// <param name="archive"></param>
    /// <param name="sourceDirectoryName"></param>
    /// <param name="zipRelativePath">在壓縮包裡面的相對路徑</param>
    /// <param name="compressionLevel"></param>
    /// <param name="fileCanAddedPredicate"></param>
    public static void AppendDirectoryToZipArchive(ZipArchive archive, string sourceDirectoryName, string zipRelativePath, CompressionLevel compressionLevel = CompressionLevel.Fastest, Predicate<string>? fileCanAddedPredicate = null)
    {
        var folders = new Stack<string>();

        folders.Push(sourceDirectoryName);

        while (folders.Count > 0)
        {
            var currentFolder = folders.Pop();

            foreach (var item in Directory.EnumerateFiles(currentFolder))
            {
                if (fileCanAddedPredicate != null && !fileCanAddedPredicate(item))
                {
                    continue;
                }

                archive.CreateEntryFromFile(item, Path.Join(zipRelativePath, Path.GetRelativePath(sourceDirectoryName, item)), compressionLevel);
            }

            foreach (var item in Directory.EnumerateDirectories(currentFolder))
            {
                folders.Push(item);
            }
        }
    }
}

以上的 C:\lindexi\Library 等資料夾是我的用於測試的資料夾,還請大家換成自己的資料夾

本文程式碼放在 githubgitee 上,可以使用如下命令列拉取程式碼

先建立一個空資料夾,接著使用命令列 cd 命令進入此空資料夾,在命令列裡面輸入以下程式碼,即可獲取到本文的程式碼

git init
git remote add origin https://gitee.com/lindexi/lindexi_gd.git
git pull origin 76bed002b4da4f363037c2d39f41596be1c2b177

以上使用的是 gitee 的源,如果 gitee 不能訪問,請替換為 github 的源。請在命令列繼續輸入以下程式碼,將 gitee 源換成 github 源進行拉取程式碼

git remote remove origin
git remote add origin https://github.com/lindexi/lindexi_gd.git
git pull origin 76bed002b4da4f363037c2d39f41596be1c2b177

獲取程式碼之後,進入 LebenehainaiJelearlowiwaw 資料夾,即可獲取到原始碼

相關文章