2012-01-06 106 views
4

我無法想象這很難做到,但我一直無法讓它工作。我有一個文件類,它只存儲我想壓縮的文件的位置,目錄和名稱。我壓縮的文件存在於磁盤上,因此FileLocation是完整路徑。 ZipFileDirectory在磁盤上不存在。如果我在我的文件列表兩個項目,DotNetZip:將文件添加到動態創建的存檔目錄

{ FileLocation = "path/file1.doc", ZipFileDirectory = @"\", FileName = "CustomName1.doc" }, 

{ FileLocation = "path/file2.doc", ZipFileDirectory = @"\NewDirectory", FileName = "CustomName2.doc" } 

我希望看到MyCustomName1.doc根,和一個文件夾命名爲含MyCustomName2.doc NewDirectory,但發生的事情是他們都在根目錄的最後使用此代碼:

using (var zip = new Ionic.Zip.ZipFile()) 
{ 
    foreach (var file in files) 
    { 
     zip.AddFile(file.FileLocation, file.ZipFileDirectory).FileName = file.FileName; 
    } 

    zip.Save(HttpContext.Current.Response.OutputStream); 
} 

如果我用這個:

zip.AddFiles(files.Select(o => o.FileLocation), false, "NewDirectory"); 

然後創建新的目錄,並把所有的文件內,符合市場預期,但後來我失去了使用C的能力ustom用這種方法命名,而且它還引入了第一種方法可以完美處理的更復雜的問題。

有沒有辦法讓我的第一個方法(AddFile())能像我期望的那樣工作?

+0

我期待通過DotNetZip代碼,並且看起來AddFile()應該工作其實像您期望。我正在考慮假設您應將'FileName'設置爲「NewDirectory \ CustomName2.doc」,但代碼不支持該假設。但是,這可能與版本有關(也許是一個錯誤)。你使用什麼版本? – phoog 2012-01-06 22:04:29

回答

7

在進一步的檢查,因爲發佈評論在幾分鐘前,我懷疑是設置FileName被清除存檔路徑。

測試證實了這一點。

將名稱設置爲@「NewDirectory \ CustomName2.doc」將解決該問題。

你也可以用@「\ NewDirectory \ CustomName2.doc」

0

不知道這是否滿足您的需求,但認爲我會分享。它是一個輔助類的一部分,我創建的輔助類使DotNetZip更易於開發團隊使用。 IOHelper類是另一個可以忽略的簡單助手類。

/// <summary> 
    /// Create a zip file adding all of the specified files. 
    /// The files are added at the specified directory path in the zip file. 
    /// </summary> 
    /// <remarks> 
    /// If the zip file exists then the file will be added to it. 
    /// If the file already exists in the zip file an exception will be thrown. 
    /// </remarks> 
    /// <param name="filePaths">A collection of paths to files to be added to the zip.</param> 
    /// <param name="zipFilePath">The fully-qualified path of the zip file to be created.</param> 
    /// <param name="directoryPathInZip">The directory within the zip file where the file will be placed. 
    /// Ex. specifying "files\\docs" will add the file(s) to the files\docs directory in the zip file.</param> 
    /// <param name="deleteExisting">Delete the zip file if it already exists.</param> 
    public void CreateZipFile(ICollection<FileInfo> filePaths, string zipFilePath, string directoryPathInZip, bool deleteExisting) 
    { 
     if (deleteExisting) 
     { 
      IOHelper ioHelper = new IOHelper(); 
      ioHelper.DeleteFile(zipFilePath); 
     } 

     using (ZipFile zip = new ZipFile(zipFilePath)) 
     { 
      foreach (FileInfo filePath in filePaths) 
      { 
       zip.AddFile(filePath.FullName, directoryPathInZip); 
      } 
      zip.Save(); 
     } 
    }  
相關問題