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#?
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.
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”.
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.
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With