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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8893891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:59:45  来源:igfitidea点击:

Add files to ZIP without paths, using SharpZipLib

c#zipsharpziplib

提问by TTCG

I need to combine 3 files into 1 zip file and make it available to download for the user. I am able to achieve my requirement except one thing: it zips the files into the subfolders.

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

For example, my files are located like the following:

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

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

But in the zip file, it zip the files in the folder by using "TTCG\WebSites\Health\" as the path. Please see the attach file.

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

Example

例子

I don't want the folders in the path. I just want 3 files in the zip file without folders. How can I achieve that?

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

My codes to generate the zip file is as below:

我生成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("~" + @"3.csv"));        

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

采纳答案by David Hoerster

Based on the FAQ, you have to strip the folder path out manually:

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

How can I create a Zip file without folders?

Remove the path portion of the filename used to create a ZipEntry before it is added to a ZipOutputStream

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

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

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

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

The FAQ can be found here.

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

It seems to be a limitation of the library. Hope this helps!

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

回答by user2237201

z.Add(pathToFile, pathInZipFile);

回答by mandostroke

If you have your files in a FileSystemInfo, you can use: z.Add(file.FullName, Path.GetFileName(file.FullName));

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

This will add your files in the root directory of your zip.

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