2017-02-21 43 views
1

我用下面的代碼片段通過Ionic.zip使ZIP文件夾:如果 :防止DotNetZip創建額外的文件夾

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

我的來源是像下面的圖片:

enter image description here

1是我的源文件夾與它的工作人員來壓縮

2-是壓縮文件夾中包含1 zip.AddDirectory(packageSpec.FolderPath, zipRoot);

但我結束於:

enter image description here

因此這些文件夾MSR->Temp->Export_1->ZipExport_1->ZipExport1是extera,這意味着Export_1.zip應該有直接源文件夾而不是嵌套的額外文件夾。

有沒有人知道我可以如何更改該代碼段來做到這一點?

在此先感謝。

回答

1

我基礎上,documentation link回答這個(尋找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) 

NOTE:

使用using語法很重要,因爲最終不會破壞ZIP文件,這可能會導致程序實際運行(如內存泄漏)的一些人員傷亡。請在MSDN上查看這篇文章 - >https://msdn.microsoft.com/en-gb/library/system.idisposable(v=vs.110).aspx?cs-lang=csharp

編輯:

因爲我真的不知道什麼是預期的結果,我無法提供你想要的。但是如果你不想要文件夾,那你爲什麼要傳遞第二個參數呢?解決方法應該是:

zip.AddDirectory(packageSpec.FolderPath); 
+0

謝謝,漂亮的修正,這是我的目標非常接近,但仍創造拉鍊版文件夾一個額外的文件夾,這樣你就可以告訴我如何糾正這種並給予一定的解釋,爲什麼這是發生? – Aria

+0

使用帶有單個參數的函數:'zip.AddDirectory(packageSpec。FolderPath);',更新的答案@Aria – Tatranskymedved

+0

好吧,我是'Ionic.Zip'的新手,無論如何感謝您的幫助我明白了。 @Tatranskymedved – Aria

相關問題