16

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?

ashwnacharya
  • 14,601
  • 23
  • 89
  • 112

4 Answers4

22

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.

Cheeso
  • 189,189
  • 101
  • 473
  • 713
  • DotNetZip is not for production. It contains some crucial bugs. I already forget which exactly, but I've concluded once after long investigations that in current state it's absolutely unreliable. – SerG Mar 23 '15 at 14:25
5

Take a look at one of these API's:

gautema
  • 634
  • 5
  • 16
5
ZipFile.CreateFromDirectory(<path of folder you need to zip>, <path of zip file with .zip in the end>, CompressionLevel.Fastest, true);
Bibaswann Bandyopadhyay
  • 3,389
  • 2
  • 31
  • 30
  • Considering `DotNetZip` and `SharpZipLib` are both abandonware, an actual .NET solution is ideal. – TEK Feb 12 '16 at 17:03
  • 1
    I can never remember the syntax for this. Don't forget to add a reference to System.IO.Compression.FileSystem and a using statement for System.IO.Compression. – Scott Jun 23 '16 at 19:12
2

You can see Article about Zip / Unzip folders and files with C#.

Anonymous
  • 9,366
  • 22
  • 83
  • 133