Search code examples
c#zipunzipextract

ExtractToDirectory , how to extract a zip folder within a zip folder using c#


Problem: I have this code that extracts all .zip folder inside a specified directory. Now my problem here is that my .zip files contains another .zip file inside of it. The output of my program is it creates a folder for the zip file extracted with a naming structure like this NUMBER_ + ZipFileName , now when I open the folder, it still contains a .zip folder inside. How do I extract a zip folder within a zip folder on the same NUMBER_ + ZipFileName Folder? It's kinda confusing to me.

desired file structure

Temp - > number_zipfilename-> [ extracted files here w/o .zip]

number_zipfilename2 - > [extraced files here w/o .zip]

.....

output of my script file structure

Temp - > number_zipfilename -> [extracted files but with .zip ]

number_zipfilename -> [extracted files but with .zip ]

Tried the recursive suggestion, but it creates another folder inside my number_zipfilename folder and the .zip file is still inside the folder.

this is my tasks requirements, its kinda hard to grasp.

this is my script

public void extractZipFiles(string targetFileDirectory, string zipFileDirectory, string Number)
{
            Directory.GetFiles(zipFileDirectory, "*.zip", SearchOption.AllDirectories).ToList()
            .ForEach(zipFilePath => {
                var test = Number + "_" + Path.GetFileNameWithoutExtension(zipFilePath);
                var extractPathForCurrentZip = Path.Combine(targetFileDirectory, test);
                if(!Directory.Exists(extractPathForCurrentZip))
                {
                    Directory.CreateDirectory(extractPathForCurrentZip);
                }
                ZipFile.ExtractToDirectory(zipFilePath, extractPathForCurrentZip);
            });
}

Solution

  • As per what I see in your code, I think you should call the extractZipFiles method recursively, so that after the extracting you call the method again with the directory where you extracted the files so it scans it for *.zip files.

    I'm not sure about what variables you'd want to use, but something like this:

    public void extractZipFiles(string targetFileDirectory, string zipFileDirectory, string Number)
    {
                Directory.GetFiles(zipFileDirectory, "*.zip", SearchOption.AllDirectories).ToList()
                .ForEach(zipFilePath => {
                    var test = Number + "_" + Path.GetFileNameWithoutExtension(zipFilePath);
                    var extractPathForCurrentZip = Path.Combine(targetFileDirectory, test);
                    if(!Directory.Exists(extractPathForCurrentZip))
                    {
                        Directory.CreateDirectory(extractPathForCurrentZip);
                    }
                    ZipFile.ExtractToDirectory(zipFilePath, extractPathForCurrentZip);
                    extractZipFiles(targetFileDirectory, extractPathForCurrentZip, Number);
                });
    }