Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create zip file from all files in folder

Tags:

c#

zip

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.

like image 593
SnelleJelle Avatar asked Sep 27 '16 19:09

SnelleJelle


People also ask

How do I zip all files in a folder?

Right-click on the file or folder. To place multiple files into a zip folder, select all of the files while hitting the Ctrl button. Then, right-click on one of the files, move your cursor over the “Send to” option and select “Compressed (zipped) folder”.


1 Answers

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));
    }              
}
like image 87
Shannon Holsinger Avatar answered Oct 07 '22 16:10

Shannon Holsinger