Creating Directories in a ZipArchive C# .Net 4.5

后端 未结 8 1898
星月不相逢
星月不相逢 2020-12-03 10:06

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 t

8条回答
  •  渐次进展
    2020-12-03 10:20

    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);
                        }
                    }
    

提交回复
热议问题