.Net - Compressing directories recursively with ICSharpCode.SharpZipLib

I think there's hardly anything to explain here or give introduction about, the title says it all. I wrote a small function to zip directories recursively using the free and open-source ICSharpCode.SharpZipLib library.

So without saying many more things, here's the function:

 

{syntaxhighlighter brush: csharp;fontsize: 100; first-line: 1; }public void addFolderToZip(ZipFile f, string root, string folder) { string relative = folder.Substring(root.Length); if (relative.Length > 0) { f.AddDirectory(relative); } foreach (string file in Directory.GetFiles(folder)) { relative = file.Substring(root.Length); f.Add(file, relative); } foreach (string subFolder in Directory.GetDirectories(folder)) { this.addFolderToZip(f, root, subFolder); } }{/syntaxhighlighter}

I will explain the parameters of the above method with an example. Suppose you have this directory structure:
C:\test\
C:\test\f1.txt
C:\test\f2.txt
C:\test\sub-folder\
C:\test\sub-folder\f3.txt
C:\test\sub-folder\f4.txt

And you want to compress the folder "test", then you can invoke the above method as follows:

 

ICSharpCode.SharpZipLib.Zip.ZipFile zipFile = ICSharpCode.SharpZipLib.Zip.ZipFile.Create("C:\\test.zip");
zipFile.BeginUpdate();

addFolderToZip(zipFile, "C:\\", "C:\\test");

zipFile.CommitUpdate();
zipFile.Close();

This will result in your zip file containing the following directory structure:
test\
test\f1.txt
test\f2.txt
test\sub-folder\
test\sub-folder\f3.txt
test\sub-folder\f4.txt 

 

As you can see, the first parameter to the method is a reference to the ICSharpCode.SharpZipLib.Zip.ZipFile object. And the third parameter is the path to the directory/folder which should be compessed.

However, the interesting parameter is the second one, "root". This is the root path relative to which the directory structure in the zip file would be created. Because we passed "C:\\" as the root path, the resulting zip file contained "test" as the base directory. Suppose we instead call the method as follows:

 

addFolderToZip(zipFile, "C:\\test\\", "C:\\test");

In this case, the resulting directory in the zip file would like:
f1.txt
f2.txt
sub-folder\
sub-folder\f3.txt
sub-folder\f4.txt

I think it should be clear now that the "root" parameter controls the parent direcory hierarchy under which the folder is zipped. Please note that the "root" has to be the same or a parent directory of the "folder" parameter.

 

 

 

Comments

Thank you so much for this tip!

Thank you for your code and good luck to you

In function addFolderToZip you should modify as bellow to avoid error:

string relative = folder.Substring(root.Length-1);

rahul's picture

Hmmm.. I am sure I was using root.Length and it was working for me. I will try to reproduce the issue if I get time. Thanks for taking time out to post your observation and fix..