SharpLibZip:添加没有路径的文件

时间:2008-10-13 17:04:34

标签: compression sharpziplib

我正在使用以下代码,使用SharpZipLib库将文件添加到.zip文件中,但每个文件都以其完整路径存储。我只需要将文件存储在.zip文件的“root”中。

string[] files = Directory.GetFiles(folderPath);
using (ZipFile zipFile = ZipFile.Create(zipFilePath))
{
     zipFile.BeginUpdate();
     foreach (string file in files)
     {
          zipFile.Add(file);
     }
     zipFile.CommitUpdate();
}

我在提供的文档中找不到任何关于此选项的内容。由于这是一个非常受欢迎的图书馆,我希望有人读这篇文章可能会有所了解。

3 个答案:

答案 0 :(得分:22)

我的解决方案是将NameTransform的{​​{1}}对象属性设置为ZipFile,并将ZipNameTransform设置为文件目录。这会导致条目名称的目录部分(完整文件路径)被删除。

TrimPrefix

NameTransform属性的类型public static void ZipFolderContents(string folderPath, string zipFilePath) { string[] files = Directory.GetFiles(folderPath); using (ZipFile zipFile = ZipFile.Create(zipFilePath)) { zipFile.NameTransform = new ZipNameTransform(folderPath); foreach (string file in files) { zipFile.BeginUpdate(); zipFile.Add(file); zipFile.CommitUpdate(); } } } 很酷,允许自定义名称转换。

答案 1 :(得分:11)

如何将System.IO.Path.GetFileName()与ZipFile.Add()的entryName参数结合使用?

string[] files = Directory.GetFiles(folderPath);
using (ZipFile zipFile = ZipFile.Create(zipFilePath))
{
     zipFile.BeginUpdate();
     foreach (string file in files)
     {
          zipFile.Add(file, System.IO.Path.GetFileName(file));
     }
     zipFile.CommitUpdate();
}

答案 2 :(得分:4)

Directory.GetFiles()的MSDN条目指出返回的文件名附加到提供的路径参数。http://msdn.microsoft.com/en-us/library/07wt70x2.aspx),因此传递给{{的字符串1}}包含路径。

根据SharpZipLib文档,Add方法存在重载,

zipFile.Add()

尝试这种方法:

public void Add(string fileName, string entryName) 
Parameters:
  fileName(String) The name of the file to add.
  entryName (String) The name to use for the ZipEntry on the Zip file created.
相关问题