Add files to ZIP without paths, using SharpZipLib

2020-08-10 07:26发布

问题:

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.

For example, my files are located like the following:

C:\TTCG\WebSites\Health\ABC.CSV
C:\TTCG\WebSites\Health\XYZ.CSV
C:\TTCG\WebSites\Health\123.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.

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?

My codes to generate the zip file is as below:

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();

回答1:

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));

The FAQ can be found here.

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



回答2:

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

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



回答3:

z.Add(pathToFile, pathInZipFile);