1

我已经使用下面的代码片段来制作 zip 文件夹Ionic.zip

string lastFolder = packageSpec.FolderPath.Split('\\')[packageSpec.FolderPath.Split('\\').Length - 1];
string zipRoot = packageSpec.FolderPath + "\\Zip" + lastFolder;
string fileName = zipRoot + "\\" + lastFolder + ".zip";
Logging.Log(LoggingMode.Prompt, "Spliting to zip part...");
if (!Directory.Exists(zipRoot))
     Directory.CreateDirectory(zipRoot);
ZipFile zip = new ZipFile();
zip.AddDirectory(packageSpec.FolderPath, zipRoot);
zip.MaxOutputSegmentSize = 200 * 1024 * 1024; // 200 MB segments
zip.Save(fileName);

它可以很好地创建多个 zip 部分,但会生成意外的嵌套文件夹,如下所示:如果变量是:

FolderPath = C:\MSR\Temp\Export_1

zipRoot = C:\MSR\Temp\Export_1\ZipExport_1

fileName= C:\MSR\Temp\Export_1\ZipExport_1\Export_1.zip

我的来源如下图所示:

在此处输入图像描述

1-是我的源文件夹,它的工作人员要压缩

2-是 zip 文件夹将包含 1zip.AddDirectory(packageSpec.FolderPath, zipRoot);

但我最终得到:

在此处输入图像描述

所以这些文件夹MSR->Temp->Export_1->ZipExport_1->ZipExport1是额外的,这意味着 Export_1.zip 应该有直接的源文件夹而不是嵌套的额外文件夹。

有谁知道我可以如何更改该代码段来做到这一点?

提前致谢。

4

1 回答 1

1

我根据文档链接回答这个问题(使用 2 个参数查找 AddDirectory):

using (ZipFile zip = new ZipFile())
{
    // files in the filesystem like MyDocuments\ProjectX\File1.txt , will be stored in the zip archive as  backup\File1.txt
    zip.AddDirectory(@"MyDocuments\ProjectX", "backup");

    // files in the filesystem like MyMusic\Santana\OyeComoVa.mp3, will be stored in the zip archive as  tunes\Santana\OyeComoVa.mp3
    zip.AddDirectory("MyMusic", "tunes");

    // The Readme.txt file in the filesystem will be stored in the zip archive as documents\Readme.txt
    zip.AddDirectory("Readme.txt", "documents");

    zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G") ;
    zip.Save(ZipFileToCreate);
}

这意味着,您的代码应如下所示:

using(ZipFile zip = new ZipFile())
{
    zip.AddDirectory(packageSpec.FolderPath, lastFolder);
    zip.Save(fileName);
}

结果:

Export_1.zip          (archive)
|-> Export_1          (folder)
    |-> Files&Folders (data)
    |-> Files&Folders (data)
    |-> Files&Folders (data)

笔记:

使用语法很重要using,因为您最终不会破坏 ZIP 文件,这可能会对程序的实际运行造成一些人员伤亡(如内存泄漏)。请查看 MSDN 上的这篇文章 -> https://msdn.microsoft.com/en-gb/library/system.idisposable(v=vs.110).aspx?cs-lang=csharp

编辑:

由于我不确定预期的结果,因此我无法提供您想要的。但是如果你不想要文件夹,那你为什么要传递第二个参数呢?解决方案应该是:

zip.AddDirectory(packageSpec.FolderPath);
于 2017-02-21T12:16:26.367 回答