Thursday, October 25, 2007

Zip a folder using SharpZipLib assembly in C#

There are several ways of zipping files. One way I started was to copy the files in the folder into an already existing zip file using a vb script. This was going fine until we had the request to delete the files when the process is done. Unfortunately the zip process thought it was completed and so the delete could start which caused the files be removed before taking the chance to be zipped.

My second attempt is this small c# script that is runnable in both frameworks 1.1 and 2.0. It uses a free open software called ZipLib that I have downloaded it from their website.

In this library they have several ways of doing the same thing. Adding files one by one was my preferred option for this particular problem but I had an issue with Windows XP not willing to show the content of the zip file whislt the file is unzippable. So I had to come up with this fast solution.

This small program is using a fast class for doing regular things like I wanted.

using System;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;

namespace ZipFolder
{
/// <summary>
/// This small program is a command line application that takes two parameters.
/// If you don't provide any parameter it will then show the syntax.
/// The aim of this class is to zip a folder with all its contents into a small zip file.
/// Notice that you can call it to zip the current folder but the destination may not be
/// within the source folder.
///
/// By Asghar Panahy
/// 25-oct-2007
///
/// </summary>
class Program
{
/// <summary>
/// Expects exactly zero or two parameters
/// </summary>
[STAThread]
static void Main(string[] args)
{
if (args.Length <2)
{
DumpSyntaxt();
return;
}

// Get the parameters
string fileName = args[0];
string path = args[1];

Console.Write(String.Format("Searching for files in {0}", path));

FastZip fZip = new FastZip();
fZip.CreateZip(fileName, path, true, "");// Still need to figure out how
he filter works!?!?!
}

private static void DumpSyntaxt()
{
Console.WriteLine("Syntaxt: Zipper.exe <zipFile>
lt;FolderPath>
");
Console.WriteLine("Exemple: Zipper.exe ..\test.zip . ");
}
}
}

3 comments:

Peter said...

nice

Guruuswa said...

the filter is easy

zip.CreateZip("uranus.zip", "c:\\uranus", true, ".*\\.(jpg|jpeg|txt|bmp|png|gif|tiff)$");

Alex said...

I know a lot of tools,which works with other type of files. But yesterday I had a problem with my zip files and I couldn't keep in mind no one of it. Fortunately I called a friend-programmer up and he recommended this application - winzip fixer. It solved my situation for minutes and free of charge as far as I remember. I hazard the remark that the tool helped my sister too and she thanked me.