Creating Directories in a ZipArchive C# .Net 4.5

后端 未结 8 1899
星月不相逢
星月不相逢 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:28

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

提交回复
热议问题