randomraccoon randomraccoon - 5 months ago 37
C# Question

How to zip a directory's contents except one subdirectory?

I'm attempting to create a zip file to serve as a backup of a directory, and eventually save that backup inside a "backups" folder in that directory. For illustration, "folder" includes "subFolder", "file1.txt", "file2.txt", and "backups". The "backups" folder would contain various earlier backup files. I want to create an archive of "folder" and all its contents, including subfolder, but exclude "backups".

Here is what I originally wanted to use:

ZipFile.CreateFromDirectory(folderToZip, backupFileName);

I realize there are problems with saving a zip file inside the folder being zipped, so I intended to save it somewhere else and then transfer it. But I don't know how to easily create an archive without the backups folder. My only thought is to write my own method recursively traversing the directory and excluding that one folder. It seems like there must be a simpler way.

Any help would be greatly appreciated!


Unfortunately, ZipFile does not offer a method that lets you filter entries. Fortunately, you can easily create a method like this based on this implementation:

public static class ZipHelper {
    public static void CreateFromDirectory(
        string sourceDirectoryName
    ,   string destinationArchiveFileName
    ,   CompressionLevel compressionLevel
    ,   bool includeBaseDirectory
    ,   Encoding entryNameEncoding
    ,   Predicate<string> filter // Add this parameter
    ) {
        if (string.IsNullOrEmpty(sourceDirectoryName)) {
            throw new ArgumentNullException("sourceDirectoryName");
        if (string.IsNullOrEmpty(destinationArchiveFileName)) {
            throw new ArgumentNullException("destinationArchiveFileName");
        var filesToAdd = Directory.GetFiles(sourceDirectoryName, "*", SearchOption.AllDirectories);
        var entryNames = GetEntryNames(filesToAdd, sourceDirectoryName, includeBaseDirectory);
        using(var zipFileStream = new FileStream(destinationArchiveFileName, FileMode.Create)) {
            using (var archive = new ZipArchive(zipFileStream, ZipArchiveMode.Create)) {
                for (int i = 0; i < filesToAdd.Length; i++) {
                    // Add the following condition to do filtering:
                    if (!filter(filesToAdd[i])) {
                    archive.CreateEntryFromFile(filesToAdd[i], entryNames[i], compressionLevel);

This implementation lets you pass a filter that rejects all entries from the "backup/" directory:

    myDir, destFile, CompressionLevel.Fastest, true, Encoding.UTF8,
    fileName => !fileName.Contains(@"\backup\")