使用SharpZipLib将文件添加到没有路径的ZIP

时间:2012-01-17 11:31:53

标签: c# zip sharpziplib

我需要将3个文件合并为1个zip文件,并为用户下载。除了一件事,我能够实现我的要求:它将文件压缩到子文件夹中。

例如,我的文件位置如下:

C:\TTCG\WebSites\Health\ABC.CSV
C:\TTCG\WebSites\Health\XYZ.CSV
C:\TTCG\WebSites\Health\123.CSV

但是在zip文件中,它使用“TTCG \ WebSites \ Health \”作为路径压缩文件夹中的文件。请参阅附件。

Example

我不想要路径中的文件夹。我只想在没有文件夹的zip文件中有3个文件。我怎样才能做到这一点?

我生成zip文件的代码如下:

ZipFile z = ZipFile.Create(Server.MapPath("~" + @"\Accident.zip"));

//initialize the file so that it can accept updates
z.BeginUpdate();

//add the file to the zip file        
z.Add(Server.MapPath("~" + @"\ABC.csv"));
z.Add(Server.MapPath("~" + @"\XYZ.csv"));
z.Add(Server.MapPath("~" + @"\123.csv"));        

//commit the update once we are done
z.CommitUpdate();
//close the file
z.Close();

3 个答案:

答案 0 :(得分:11)

根据常见问题解答,您必须手动删除文件夹路径:

  

如何创建没有文件夹的Zip文件?

     

删除用于创建ZipEntry的文件名的路径部分   在将其添加到ZipOutputStream

之前      

ZipEntry entry = new ZipEntry(Path.GetFileName(fullPath));

常见问题解答here

这似乎是图书馆的限制。希望这有帮助!

答案 1 :(得分:3)

如果您的文件位于FileSystemInfo中,则可以使用:z.Add(file.FullName, Path.GetFileName(file.FullName));

这会将您的文件添加到zip的根目录中。

答案 2 :(得分:1)

z.Add(pathToFile, pathInZipFile);
相关问题