Unzip all .zip archives in a directory

2k Views Asked by At

I am struggling to configure a script to unzip all .zip archives in a directory and place the extracted files into a different directory. I am wanting to schedule this script to run on a schedule to handle incoming .zip archives.

For each .zip file in the source directory, I need it to extract those files to the destination, then repeat until all .zip files have been processed.

Here is my horrible attempt.

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

namespace Unzipper
{
class Program
  {
    static void Main(string[] args)
    {
        string startPath = @"C:\zipdirectory\";

        foreach(String file in Directory.GetFiles(startPath, "*.zip", SearchOptions.AllDirectories)){allFiles.Add(file);

        string zipPath = @"(output from above??)

        string extractPath = @"C:\unzipdirectory\";

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

There are 1 best solutions below

1
On

Firstly, you get all .zip file in the startPath

For each path, unzip it to a new folder created by a combination like C:\unzipdirectory\<zip_file_name_without_extension_zip>

static void Main(string[] args)
    {
        string startPath = @"C:\zipdirectory\";
        string extractPath = @"C:\unzipdirectory\";
        Directory.GetFiles(startPath, "*.zip", SearchOptions.AllDirectories).ToList()
            .ForEach(zipFilePath => {
                var extractPathForCurrentZip = Path.Combine(extractPath, Path.GetFileNameWithoutExtension(zipFilePath));
                if(!Directory.Exists(extractPathForCurrentZip))
                {
                    Directory.CreateDirectory(extractPathForCurrentZip);
                }
                ZipFile.ExtractToDirectory(zipFilePath, extractPathForCurrentZip);
        });
    }