Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add files to ZIP without paths, using SharpZipLib

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();
like image 291
TTCG Avatar asked Jan 17 '12 11:01

TTCG


3 Answers

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!

like image 151
David Hoerster Avatar answered Nov 16 '22 12:11

David Hoerster


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.

like image 28
mandostroke Avatar answered Nov 16 '22 10:11

mandostroke


z.Add(pathToFile, pathInZipFile);
like image 2
user2237201 Avatar answered Nov 16 '22 11:11

user2237201