Add files to ZIP without paths, using SharpZipLib
Asked Answered
E

3

14

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.

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?

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();
Eastereasterday answered 17/1, 2012 at 11:31 Comment(0)
O
11

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!

Ovoid answered 17/1, 2012 at 11:41 Comment(0)
U
3

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.

Uncloak answered 26/8, 2013 at 16:22 Comment(1)
@MatthewLock that method takes 2 strings like that for me. SharpZipLib v0.86.0.518Coumas
C
2
z.Add(pathToFile, pathInZipFile);
Celebrant answered 6/5, 2013 at 19:9 Comment(1)
This doesn't compile the Add method doesn't take 2 strings like thatOutwash

© 2022 - 2024 — McMap. All rights reserved.