Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I Compress a directory with .NET?

I have a directory that contains several files. I want compress this folder to a zip or tar.gz file. How can I do his work in C#?

like image 538
masoud ramezani Avatar asked Feb 10 '10 10:02

masoud ramezani


People also ask

How do I compress a directory?

Locate the file or folder that you want to zip. 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.

Can you compress an entire folder?

Right-click on the file or folder.Select “Compressed (zipped) 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”.


2 Answers

The question is quite old and so are the answers.

Best answer since end of 2012 is: Use .NET 4.5 and the contained System.IO.Compression and System.IO.Compression.ZipArchive namespace classes.

One of many example links you receive if you search in the internet: http://www.codeproject.com/Articles/381661/Creating-Zip-Files-Easily-in-NET

Since 2014/2015 ff.: With Roslyn the whole framework library was published as Open Source, so AFAI understand it, you are free to extract the code from the 4.5 classes (as it should be not really system specific) and use it as a library for the earlier .NET frameworks. Maybe this would give some license advantages over using the other classes- but this has to be analyzed by you.

like image 179
Philm Avatar answered Oct 26 '22 06:10

Philm


You can use DotNetZip Library. It has quite rich and useful features.


EDIT:

string[] MainDirs = Directory.GetDirectories(DirString);

for (int i = 0; i < MainDirs.Length; i++)
{
    using (ZipFile zip = new ZipFile())
    {
        zip.UseUnicodeAsNecessary = true;
        zip.AddDirectory(MainDirs[i]);
        zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
        zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G");
        zip.Save(string.Format("test{0}.zip", i));   
    }
}
like image 33
Giorgi Avatar answered Oct 26 '22 07:10

Giorgi