Create zip file from all files in folder

SnelleJelle picture SnelleJelle · Sep 27, 2016 · Viewed 21.8k times · Source

I'm trying to create a zip file from all files in a folder, but can't find any related snippet online. I'm trying to do something like this:

DirectoryInfo dir = new DirectoryInfo("somedir path");
ZipFile zip = new ZipFile();
zip.AddFiles(dir.getfiles());
zip.SaveTo("some other path");

Any help is very much appreciated.

edit: I only want to zip the files from a folder, not it's subfolders.

Answer

Shannon Holsinger picture Shannon Holsinger · Sep 27, 2016

Referencing System.IO.Compression and System.IO.Compression.FileSystem in your Project

using System.IO.Compression;

string startPath = @"c:\example\start";//folder to add
string zipPath = @"c:\example\result.zip";//URL for your ZIP file
ZipFile.CreateFromDirectory(startPath, zipPath, CompressionLevel.Fastest, true);
string extractPath = @"c:\example\extract";//path to extract
ZipFile.ExtractToDirectory(zipPath, extractPath);

To use files only, use:

//Creates a new, blank zip file to work with - the file will be
//finalized when the using statement completes
using (ZipArchive newFile = ZipFile.Open(zipName, ZipArchiveMode.Create))
{
    foreach (string file in Directory.GetFiles(myPath))
    {
        newFile.CreateEntryFromFile(file, System.IO.Path.GetFileName(file));
    }              
}