Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compress a directory into a zip file programmatically

Tags:

c#

.net

zip

gzip

I want to compress an entire directory which can have any number of subdirectories into a single ZIP file.

I am able to compress a single file into a zip file programmatically.

To compress an entire directory, i can think of a recursive program that walks through each subdirectory and compresses it.

But Is there any simple way to compress the entire folder using the similar code, without having to write any recursive functions?

like image 991
ashwnacharya Avatar asked Mar 23 '10 09:03

ashwnacharya


People also ask

How do I compress a folder into a zip file?

Press and hold (or right-click) the file or folder, select (or point to) Send to, and then select Compressed (zipped) folder. A new zipped folder with the same name is created in the same location. To rename it, press and hold (or right-click) the folder, select Rename, and then type the new name.


2 Answers

Using DotNetZip, there's an AddDirectory() method on the ZipFile class that does what you want:

using (var zip = new Ionic.Zip.ZipFile())
{
    zip.AddDirectory("DirectoryOnDisk", "rootInZipFile");
    zip.Save("MyFile.zip");
}

This example, and many others, are available on codeplex.

like image 128
Cheeso Avatar answered Oct 16 '22 19:10

Cheeso


Take a look at one of these API's:

  • DotNetZip
  • SharpZipLib
like image 40
gautema Avatar answered Oct 16 '22 18:10

gautema