Ionic Zip - 打包整个目录,保留子目录并遍历所有文件

本文关键字:子目录 遍历 文件 保留 Zip 包整个 Ionic | 更新日期: 2023-09-27 18:35:58

我想使用 Ionic Zip 在 C# 中打包一个目录。通常我只会使用这段代码:

using (ZipFile pack = new ZipFile())
{      
    pack.AddDirectory(defPackageCreationPath + "''installfiles", "");            
    pack.Save(outputPath + "''package.mpp");
}

这工作正常,但是我需要遍历每个正在打包的文件以检查其文件名中的字符,因为我有一些文件在打包时会损坏,如果它们包含特定字符。

同样重要的是,要添加的目录也包含子目录,这些子目录需要转移到zip文件中并在其中创建。

如何?

Ionic Zip - 打包整个目录,保留子目录并遍历所有文件

不确定这是否是您正在寻找的,但您可以轻松获取所有文件(包括子目录)的字符串数组。 使用目录类

这样

string[] Files = Directory.GetFiles(@"M:'Backup", "*.*", SearchOption.AllDirectories);
foreach (string file in Files)
{
    DoTests(file);
}

这将包括文件的路径。

您将需要 System.IO;

using System.IO;

你也可以尝试这样的事情:

using (ZipFile pack = new ZipFile())
{
    pack.AddProgress += (s, eventArgs) =>
        {
            // check if EventType is Adding_AfterAddEntry or NullReferenceException will be thrown
            if (eventArgs.EventType == ZipProgressEventType.Adding_AfterAddEntry)
            {
                // Do the replacement here.
                // eventArgs.CurrentEntry is the current file processed and
                // eventArgs.CurrentEntry.FileName holds the file name
                //
                // Example: all files will begin with __
                eventArgs.CurrentEntry.FileName = "___" + eventArgs.CurrentEntry.FileName;
            }
        };
        pack.AddDirectory(defPackageCreationPath + "''installfiles", "");            
        pack.Save(outputPath + "''package.mpp");
    }
}