Compressing Files and Folders with SharpZipLib

I have found a lot of examples on how to compress files using C# but only a few that would compress all files and folders (including subfolders). I found an example in this forum that show how to do it using SharpZipLib.

Here is what I did with it:

static void Main(string[] args)
{
    ZipOutputStream zip = new ZipOutputStream(File.Create(@"d:\my.zip"));
    zip.SetLevel(9);
    string folder = @"D:\Work\AnyDirectory\";
    ZipFolder(folder, folder, zip);
    zip.Finish();
    zip.Close();
}

public static void ZipFolder(string RootFolder, string CurrentFolder, 
    ZipOutputStream zStream)
{
    string[] SubFolders = Directory.GetDirectories(CurrentFolder);

    //calls the method recursively for each subfolder
    foreach (string Folder in SubFolders)
    {
        ZipFolder(RootFolder, Folder, zStream);
    }

    string relativePath = CurrentFolder.Substring(RootFolder.Length) + "/";

    //the path "/" is not added or a folder will be created
    //at the root of the file
    if (relativePath.Length > 1)
    {
        ZipEntry dirEntry;
        dirEntry = new ZipEntry(relativePath);
        dirEntry.DateTime = DateTime.Now;
    }

    //adds all the files in the folder to the zip
    foreach (string file in Directory.GetFiles(CurrentFolder))
    {
        AddFileToZip(zStream, relativePath, file);
    }
}

private static void AddFileToZip(ZipOutputStream zStream, string relativePath, string file)
{
    byte[] buffer = new byte[4096];

    //the relative path is added to the file in order to place the file within
    //this directory in the zip
    string fileRelativePath = (relativePath.Length > 1 ? relativePath : string.Empty) 
                              + Path.GetFileName(file);

    ZipEntry entry = new ZipEntry(fileRelativePath);
    entry.DateTime = DateTime.Now;
    zStream.PutNextEntry(entry);

    using (FileStream fs = File.OpenRead(file))
    {
        int sourceBytes;
        do
        {
            sourceBytes = fs.Read(buffer, 0, buffer.Length);
            zStream.Write(buffer, 0, sourceBytes);
        } while (sourceBytes > 0);
    }
}

This is not hard but I had to figure out that the file names needed to have the relative path before it in order to correctly place them in the same folders within the compressed zip file.

I hope this helps!

Comments

Posted by: David Treves
On: 3/8/2010 7:38:16 AM

Hi,

Thanks for that! Saved me some precious time! :)

Questions / observations:

1 - What are you doing with the ZipEntry that you created in line 28? Seems unnecessary, no?

2. For non-English directory/file names you should set for the ZipEntry at line 49 the following: entry.IsUnicodeText = true;

Thanks again,
David.

Leave your comment

Author

Email (never displayed)

Website

Comment  
HTML is NOT allowed. Use regular line breaks and those will be respected.