Creating Directories in a ZipArchive C# .Net 4.5

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

    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 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 + "/");
        }
    }
    

提交回复
热议问题