SharpZipLib compression in C#

I have recently been playing around with SharpZipLib, an open source compression library for C#.

Below is some code demonstrating how to recursively zip folders and subfolders. If an exception is thrown (i.e if a file is open when you try and zip it), it copies the file to a temp directory and zips it from there.

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

    foreach (string Folder in SubFolders)
    {
        ZipFolder(Root, Folder, ZipStream);
    }

    string path = CurrentFolder.Substring(Root.Length) + "/";

    if (path.Length > 1)
    {
        ZipEntry zEntry;
        zEntry = new ZipEntry(path);
        zEntry.DateTime = DateTime.Now;
    }

    foreach (string file in Directory.GetFiles(CurrentFolder))
    {
        ZipFile(ZipStream, path, file);
    }
}

private static void ZipFile(ZipOutputStream ZipStream, string path, string file)
{
    try
    {
        byte[] buffer = new byte[4096];
        string filePath = (path.Length > 1 ? path : string.Empty) + Path.GetFileName(file);
        ZipEntry zEntry = new ZipEntry(filePath);

        zEntry.DateTime = DateTime.Now;

        ZipStream.PutNextEntry(zEntry);

        using (FileStream fs = File.OpenRead(file))
        {
            int sourceBytes;
            do
            {
                sourceBytes = fs.Read(buffer, 0, buffer.Length);
                ZipStream.Write(buffer, 0, sourceBytes);
            }
            while (sourceBytes > 0);
        }
    }
    catch (Exception)
    {
        if (File.Exists(file))
        {
            File.Copy(file, @"C:\TEMP\" + Path.GetFileName(file), true);
            ZipFile(ZipStream, path, @"C:\TEMP\" + Path.GetFileName(file));
        }
    }
}
Advertisements