2

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);
    }
  }
}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
meckley
  • 21
  • 2

1 Answers1

2

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);
        });
    }
Antoine V
  • 6,998
  • 2
  • 11
  • 34
  • what if my zip file contains another .zip file inside of it? I tried your solution but it does not extract the .zip file inside of it. – keinz May 18 '20 at 07:27