【问题标题】:Prevent DotNetZip to create extra folder防止 DotNetZip 创建额外的文件夹
【发布时间】:2017-07-11 00:06:19
【问题描述】:

我已经使用下面的 sn-p 代码通过Ionic.zip 制作 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 文件夹将包含 1 个zip.AddDirectory(packageSpec.FolderPath, zipRoot);

但我的结局是:

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

有人知道我可以如何更改该 sn-p 代码来做到这一点吗?

提前致谢。

【问题讨论】:

    标签: c# zip directory dotnetzip ionic-zip


    【解决方案1】:

    我是根据documentation link 来回答这个问题的(寻找带有 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);
    

    【讨论】:

    • 谢谢,很好的更正,这非常接近我的目标,但仍然在压缩文件夹中创建一个额外的文件夹,所以你能告诉我这是多么正确并解释为什么会这样吗?
    • 使用单参数函数:zip.AddDirectory(packageSpec.FolderPath);,更新答案@Aria
    • 好的,我是Ionic.Zip 的新手,谢谢你的帮助,我明白了。 @Tatranskymedved
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-20
    相关资源
    最近更新 更多