views:

213

answers:

8

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#?

+1  A: 

At my previous job we used #ziplib.

Gerrie Schenck
+1  A: 

use 7zip from commandline in C# --> LZMA SDK supports C#, and there are codesamples in the package

Natrium
+3  A: 

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));   
    }
}
Giorgi
Just added some sample code to the answer, hope you don't mind.
Kyle Rozendo
+4  A: 

Look into using SharpZipLib. It supports both GZip and ZIP compression in C#.

There is an excellent tutorial here outlining what you need to do to zip a directory with SharpZipLib.

Daniel May
A: 

This is a good discussion that discusses the possibility of doing this without any third party libraries. I think you should have a look on it.

Here is a large repository of sample codes that can help you in your work. Good Luck..

Chathuranga Chandrasekara
A: 

i use the System.IO.Packaging Namespace which was introduced with .NET Framework 3.5. I decided to use that one because it's based on .NET Framework Base classes and no 3rd party code is required which blows up the size of the code..

here's another post on Stackoverflow regarding this Question

And here's the Namespace and ZipPackage declaration / explanation @MSDN

hope that helps

Christian

Christian
A: 

GZip is part of Microsoft Framework 2.0 onward. Its called GZipStream under System.IO.Compression namespace.

To compress a directory with this class, you'd have to create a serializable class (for e.g. Directory) which contains a collection of Files.

The Files class would contain file-name and file-stream to read bytes from file. Once you do apply GZip on the Directory, it'll read Files one by one and write them to GZipStream.

Check this link: http://www.vwd-cms.com/forum/forums.aspx?topic=18

cornerback84
A: 

Another pre-3.5 option is to use the zip utilities from J#. After all, .Net doesn't care what language the code was originally written in ;-).

Articles on how to do this:

Peter Stuer