43

A ZipArchive is a collection of ZipArchiveEntries, and adding/removing "Entries" works nicely. But it appears there is no notion of directories / nested "Archives". In theory, the class is decoupled from a file system, in that you can create the archive completely in a memory stream. But if you wish to add a directory structure within the archive, you must prefix the entry name with a path.

Question: How would you go about extending ZipArchive to create a better interface for creating and managing directories?

For example, the current method of adding a file to a directory is to create the entry with the directory path:

var entry = _archive.CreateEntry("directory/entryname");

whereas something along these lines seems nicer to me:

var directory = _archive.CreateDirectoryEntry("directory");
var entry = _directory.CreateEntry("entryname");
Meirion Hughes
  • 24,994
  • 12
  • 71
  • 122

11 Answers11

71

You can use something like the following, in other words, create the directory structure by hand:

using (var fs = new FileStream("1.zip", FileMode.Create))
using (var zip = new ZipArchive(fs, ZipArchiveMode.Create))
{
    zip.CreateEntry("12/3/"); // just end with "/"
}
Abel
  • 56,041
  • 24
  • 146
  • 247
Aimeast
  • 1,609
  • 14
  • 29
27

I know I'm late to the party (7.25.2018),

this works flawlessly to me, even with recursive directories.

Firstly, remember to install the NuGet package:

Install-Package System.IO.Compression

And then, Extension file for ZipArchive:

 public static class ZipArchiveExtension {

     public static void CreateEntryFromAny(this ZipArchive archive, string sourceName, string entryName = "") {
         var fileName = Path.GetFileName(sourceName);
         if (File.GetAttributes(sourceName).HasFlag(FileAttributes.Directory)) {
             archive.CreateEntryFromDirectory(sourceName, Path.Combine(entryName, fileName));
         } else {
             archive.CreateEntryFromFile(sourceName, Path.Combine(entryName, fileName), CompressionLevel.Fastest);
         }
     }

     public static void CreateEntryFromDirectory(this ZipArchive archive, string sourceDirName, string entryName = "") {
         string[] files = Directory.GetFiles(sourceDirName).Concat(Directory.GetDirectories(sourceDirName)).ToArray();
         foreach (var file in files) {
             archive.CreateEntryFromAny(file, entryName);
         }
     }
 }

And then you can pack anything, whether it is file or directory:

using (var memoryStream = new MemoryStream()) {
    using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) {
        archive.CreateEntryFromAny(sourcePath);
    }
}
Necas209
  • 3
  • 4
Val
  • 21,938
  • 10
  • 68
  • 86
10

If you are working on a project that can use full .NET you may try to use the ZipFile.CreateFromDirectory method, as explained here:

using System;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string startPath = @"c:\example\start";
            string zipPath = @"c:\example\result.zip";
            string extractPath = @"c:\example\extract";

            ZipFile.CreateFromDirectory(startPath, zipPath, CompressionLevel.Fastest, true);

            ZipFile.ExtractToDirectory(zipPath, extractPath);
        }
    }
}

Of course this will only work if you are creating new Zips based on a given directory.

As per the comment, the previous solution does not preserve the directory structure. If that is needed, then the following code might address that:

    var InputDirectory = @"c:\example\start";
    var OutputFilename = @"c:\example\result.zip";
    using (Stream zipStream = new FileStream(Path.GetFullPath(OutputFilename), FileMode.Create, FileAccess.Write))
    using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Create))
    {
        foreach(var filePath in System.IO.Directory.GetFiles(InputDirectory,"*.*",System.IO.SearchOption.AllDirectories))
        {
            var relativePath = filePath.Replace(InputDirectory,string.Empty);
            using (Stream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            using (Stream fileStreamInZip = archive.CreateEntry(relativePath).Open())
                fileStream.CopyTo(fileStreamInZip);
        }
    }
hmadrigal
  • 1,020
  • 11
  • 19
  • 4
    Just a pedantic note on this, something I've found after some fiddling. It doesn't work *exactly* as a standard "Sent To->Compressed file" does on a windows desktop. Windows SendTo will create entries for the directories in the structure explicitly, where as this method maintains directory structure implicitly, i.e. it doesn't create entries for the directories, but directories are listed in the full path to each file. It doesn't change the way the winzip function works (it's happy to work with either) but it's just a matter of being aware if you're expecting a specific file structure. – Andy Bullivent Mar 08 '17 at 08:53
  • Thanks. Saved me lots of time. I just did a small edit to the code, hope you accept it. I added Substring(1) to getting the relative path, to make the zip file browseable. – A Khudairy Oct 31 '17 at 08:26
8

Here is one possible solution:

public static class ZipArchiveExtension
{
    public static ZipArchiveDirectory CreateDirectory(this ZipArchive @this, string directoryPath)
    {
        return new ZipArchiveDirectory(@this, directoryPath);
    }
}

public class ZipArchiveDirectory
{
    private readonly string _directory;
    private ZipArchive _archive;

    internal ZipArchiveDirectory(ZipArchive archive, string directory)
    {
        _archive = archive;
        _directory = directory;
    }

    public ZipArchive Archive { get{return _archive;}}

    public ZipArchiveEntry CreateEntry(string entry)
    {
        return _archive.CreateEntry(_directory + "/" + entry);
    }

    public ZipArchiveEntry CreateEntry(string entry, CompressionLevel compressionLevel)
    {
        return _archive.CreateEntry(_directory + "/" + entry, compressionLevel);
    }
}

and used:

var directory = _archive.CreateDirectory(context);
var entry = directory.CreateEntry(context);
var stream = entry.Open();

but I can foresee problems with nesting, perhaps.

Meirion Hughes
  • 24,994
  • 12
  • 71
  • 122
3

I was also looking for a similar solution and found @Val & @sDima's solution more promising to me. But I found some issues with the code and fixed them to use with my code.

Like @sDima, I also decided to use Extension to add more functionality to ZipArchive.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Compression;
using System.IO;

namespace ZipTest
{
   public static class ZipArchiveExtensions
   {
      public static void CreateEntryFromAny(this ZipArchive archive, string sourceName, string entryName, CompressionLevel compressionLevel = CompressionLevel.Optimal)
    {
        try
        {
            if (File.GetAttributes(sourceName).HasFlag(FileAttributes.Directory))
            {
                archive.CreateEntryFromDirectory(sourceName, entryName, compressionLevel);
            }
            else
            {
                archive.CreateEntryFromFile(sourceName, entryName, compressionLevel);
            }
        }
        catch
        {
            throw;
        }
    }

    public static void CreateEntryFromDirectory(this ZipArchive archive, string sourceDirName, string entryName, CompressionLevel compressionLevel)
    {
        try
        {
            var files = Directory.EnumerateFileSystemEntries(sourceDirName);
            if (files.Any())
            {
                foreach (var file in files)
                {
                    var fileName = Path.GetFileName(file);
                    archive.CreateEntryFromAny(file, Path.Combine(entryName, fileName), compressionLevel);
                }
            }
            else
            {
                //Do a folder entry check.
                if (!string.IsNullOrEmpty(entryName) && entryName[entryName.Length - 1] != '/')
                {
                    entryName += "/";
                }

                archive.CreateEntry(entryName, compressionLevel);
            }
        }
        catch
        {
            throw;
        }
      }
    }
  }

You can try the extension using the simple given below,

 class Program
 {
    static void Main(string[] args)
    {
        string filePath = @"C:\Users\WinUser\Downloads\Test.zip";
        string dirName = Path.GetDirectoryName(filePath);
       
        if (File.Exists(filePath))
            File.Delete(filePath);

        using (ZipArchive archive = ZipFile.Open(filePath, ZipArchiveMode.Create))
        {
            archive.CreateEntryFromFile( @"C:\Users\WinUser\Downloads\file1.jpg", "SomeFolder/file1.jpg", CompressionLevel.Optimal);
            archive.CreateEntryFromDirectory(@"C:\Users\WinUser\Downloads\MyDocs", "OfficeDocs", CompressionLevel.Optimal);
            archive.CreateEntryFromAny(@"C:\Users\WinUser\Downloads\EmptyFolder", "EmptyFolder", CompressionLevel.Optimal);
        };

        using (ZipArchive zip = ZipFile.OpenRead(filePath))
        {
            string dirExtract = @"C:\Users\WinUser\Downloads\Temp";
            if (Directory.Exists(dirExtract))
            {
                Directory.Delete(dirExtract, true);
            }

            zip.ExtractToDirectory(dirExtract);
        }
     }
   }

I tried to keep the exact behavior of standard CreateEntryFromFilefrom the .Net Framework for extension methods.

To use the sample code given, add a reference to System.IO.Compression.dll and System.IO.Compression.FileSystem.dll.

Following are the advantages of this extension class

  1. Recursive adding of folder content.
  2. Support for an empty folder.
Nitheesh George
  • 1,357
  • 10
  • 13
3

A little change in the very good approach from @Andrey

public static void CreateEntryFromDirectory2(this ZipArchive archive, string sourceDirName, CompressionLevel compressionLevel = CompressionLevel.Fastest)
    {
        var folders = new Stack<string>();

        folders.Push(sourceDirName);

        do
        {
            var currentFolder = folders.Pop();

            foreach (var item in Directory.GetFiles(currentFolder))
            {
                archive.CreateEntryFromFile(item, item.Substring(sourceDirName.Length + 1), compressionLevel);
            }

            foreach (var item in Directory.GetDirectories(currentFolder))
            {
                folders.Push(item);
            }
        } 
        while (folders.Count > 0);
    }
Murilo Maciel Curti
  • 2,677
  • 1
  • 21
  • 26
2

My answer is based on the Val's answer, but a little improved for performance and without producing empty files in ZIP.

public static class ZipArchiveExtensions
{
    public static void CreateEntryFromAny(this ZipArchive archive, string sourceName, string entryName = "")
    {
        var fileName = Path.GetFileName(sourceName);
        if (File.GetAttributes(sourceName).HasFlag(FileAttributes.Directory))
        {
            archive.CreateEntryFromDirectory(sourceName, Path.Combine(entryName, fileName));
        }
        else
        {
            archive.CreateEntryFromFile(sourceName, Path.Combine(entryName, fileName), CompressionLevel.Optimal);
        }
    }

    public static void CreateEntryFromDirectory(this ZipArchive archive, string sourceDirName, string entryName = "")
    {
        var files = Directory.EnumerateFileSystemEntries(sourceDirName);
        foreach (var file in files)
        {
            archive.CreateEntryFromAny(file, entryName);
        }
    }
}

Example of using:

// Create and open a new ZIP file
                using (var zip = ZipFile.Open(ZipPath, ZipArchiveMode.Create))
                {
                    foreach (string file in FILES_LIST)
                    {
                        // Add the entry for each file
                        zip.CreateEntryFromAny(file);
                    }
                }
sDima
  • 356
  • 2
  • 16
2

One more tuned ZipArchive extension, which adds folder structure including all subfolders and files to zip. Solved IOException (Process can't access the file...) which is thrown if files are in use at zipping moment, for example by some logger

public static class ZipArchiveExtensions
{
    public static void AddDirectory(this ZipArchive @this, string path)
    {
        @this.AddDirectory(path, string.Empty);
    }

    private static void AddDirectory(this ZipArchive @this, string path, string relativePath)
    {
        var fileSystemEntries = Directory.EnumerateFileSystemEntries(path);

        foreach (var fileSystemEntry in fileSystemEntries)
        {
            if (File.GetAttributes(fileSystemEntry).HasFlag(FileAttributes.Directory))
            {
                @this.AddDirectory(fileSystemEntry, Path.Combine(relativePath, Path.GetFileName(fileSystemEntry)));
                continue;
            }

            var fileEntry = @this.CreateEntry(Path.Combine(relativePath, Path.GetFileName(fileSystemEntry)));

            using (var zipStream = fileEntry.Open())
            using (var fileStream = new FileStream(fileSystemEntry, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            using (var memoryStream = new MemoryStream())
            {
                fileStream.CopyTo(memoryStream);

                var bytes = memoryStream.ToArray();
                zipStream.Write(bytes, 0, bytes.Length);
            }
        }
    }
}
Piwnik
  • 181
  • 1
  • 5
  • 1
    I changed the second method to public in my code. I also removed the memory stream since I don't want to read the entire file to RAM: `fileStream.CopyTo(zipStream);` – andasa Feb 05 '21 at 07:34
1

Use the recursive approach to Zip Folders with Subfolders.

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;

public static async Task<bool> ZipFileHelper(IFolder folderForZipping, IFolder folderForZipFile, string zipFileName)
{
    if (folderForZipping == null || folderForZipFile == null
        || string.IsNullOrEmpty(zipFileName))
    {
        throw new ArgumentException("Invalid argument...");
    }

    IFile zipFile = await folderForZipFile.CreateFileAsync(zipFileName, CreationCollisionOption.ReplaceExisting);

    // Create zip archive to access compressed files in memory stream
    using (MemoryStream zipStream = new MemoryStream())
    {
        using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
        {
            await ZipSubFolders(folderForZipping, zip, "");
        }

        zipStream.Position = 0;
        using (Stream s = await zipFile.OpenAsync(FileAccess.ReadAndWrite))
        {
            zipStream.CopyTo(s);
        }
    }
    return true;
}

//Create zip file entry for folder and subfolders("sub/1.txt")
private static async Task ZipSubFolders(IFolder folder, ZipArchive zip, string dir)
{
    if (folder == null || zip == null)
        return;

    var files = await folder.GetFilesAsync();
    var en = files.GetEnumerator();
    while (en.MoveNext())
    {
        var file = en.Current;
        var entry = zip.CreateEntryFromFile(file.Path, dir + file.Name);                
    }

    var folders = await folder.GetFoldersAsync();
    var fEn = folders.GetEnumerator();
    while (fEn.MoveNext())
    {
        await ZipSubFolders(fEn.Current, zip, dir + fEn.Current.Name + "/");
    }
}
Hack ok
  • 11
  • 2
1

I don't like recursion as it was proposed by @Val, @sDima, @Nitheesh. Potentially it leads to the StackOverflowException because the stack has limited size. So here is my two cents with tree traversal.

public static class ZipArchiveExtensions
{
    public static void CreateEntryFromDirectory(this ZipArchive archive, string sourceDirName, CompressionLevel compressionLevel = CompressionLevel.Fastest)
    {
        var folders = new Stack<string>();
        folders.Push(sourceDirName);
        
        do
        {
            var currentFolder = folders.Pop();
            Directory.GetFiles(currentFolder).ForEach(f => archive.CreateEntryFromFile(f, f.Substring(sourceDirName.Length+1), compressionLevel));
            Directory.GetDirectories(currentFolder).ForEach(d => folders.Push(d));
        } while (folders.Count > 0);
    }
}
Andrey Burykin
  • 700
  • 11
  • 23
0

It's working for me.

Static class

public static class ZipArchiveExtension
{

    public static void CreateEntryFromAny(this ZipArchive archive, string sourceName, string entryName = "")
    {
        var fileName = Path.GetFileName(sourceName);            
        if (File.GetAttributes(sourceName).HasFlag(FileAttributes.Directory))
        {
            archive.CreateEntryFromDirectory(sourceName, Path.Combine(entryName, fileName));
        }
        else
        {
            archive.CreateEntryFromFile(sourceName, Path.Combine(entryName, fileName), CompressionLevel.Fastest);
        }
    }

    public static void CreateEntryFromDirectory(this ZipArchive archive, string sourceDirName, string entryName = "")
    {
        string[] files = Directory.GetFiles(sourceDirName).Concat(Directory.GetDirectories(sourceDirName)).ToArray();

        if (files.Any())
        {

            foreach (var file in files)
            {
                archive.CreateEntryFromAny(file, entryName);
            }
        }
        else
        {
            if (!string.IsNullOrEmpty(entryName) && entryName[entryName.Length - 1] != '/')
            {
                entryName += "\\";
            }
            archive.CreateEntry(entryName);
        }
        
    }
}

Calling the method like that

            byte[] archiveFile;

            using (var memoryStream = new MemoryStream())
            {
                using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                {
                        archive.CreateEntryFromAny(file.Path);

                }
                archiveFile = memoryStream.ToArray();
            }