14

我需要将 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\”作为路径来压缩文件夹中的文件。请看附件。

例子

我不想要路径中的文件夹。我只想要 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();
4

3 回答 3

11

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

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

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

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

可以在此处找到常见问题解答。

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

于 2012-01-17T11:41:29.560 回答
3

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

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

于 2013-08-26T16:22:35.493 回答
2
z.Add(pathToFile, pathInZipFile);
于 2013-05-06T19:09:13.050 回答