Trying Zip different folders in in a specified directory using ZipFile

1.4k Views Asked by At

I found the code below on stack overflow which I tried but didn't know how to use it fully.

Basically I want to be able to zip all the files separately using foreach loop but I won't have a list of the files as they change each time.

So how can I get a list of the folders/directories inside the root directory into an array?

public static void CreateZipFile(string fileName, IEnumerable<string> files)
{
    var zip = ZipFile.Open(fileName, ZipArchiveMode.Create);
    foreach (var file in files)
    {
        zip.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal);
    }

    zip.Dispose();
}
2

There are 2 best solutions below

3
On BEST ANSWER

Normally I just use DotNetZip
And this code:

using (var file = new ZipFile(zipName))
{
    file.AddFiles(fileNames, directoryPathInArchive);
    file.Save();
}

Where zipName is the name of zip archive you want to create and fileNames are names of files you want to put in it.

0
On

you need little script for this

public static class ZipUtil
{
    public static void CreateFromMultifleFolders(string targetZip, string[] foldersSrc, string[] fileSrc = null, CompressionLevel compressionLevel = CompressionLevel.Fastest)
    {
        if (File.Exists(targetZip))
            File.Delete(targetZip);

        using (ZipArchive archive = ZipFile.Open(targetZip, ZipArchiveMode.Create))
        {
            foreach (string dir in foldersSrc)
                AddFolederToZip(dir, archive, Path.GetFileName(dir), compressionLevel);

            if(fileSrc != null)
                foreach (string file in fileSrc)
                    archive.CreateEntryFromFile(file, Path.GetFileName(file), compressionLevel);
        }
    }

    private static void AddFolederToZip(string folder, ZipArchive archive, string srcPath, CompressionLevel compressionLevel)
    {
        srcPath += "/";

        foreach (string dir in Directory.GetDirectories(folder))
            AddFolederToZip(dir, archive, srcPath + Path.GetFileName(dir), compressionLevel);

        foreach (string file in Directory.GetFiles(folder))
            archive.CreateEntryFromFile(file, srcPath + Path.GetFileName(file), compressionLevel);
    }
}