2012-01-06 109 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(); 
     } 
    }  
相关问题