Search code examples
c#extractunzipzip

Check Zip File content and extract


Hi I want to extract a ZipFile that has various of text files. But i could be that de text files are in a folder. So what i want to do is: If an folder exists just exract normaly if not create a folder with name of ZipFile. The reason is i don't want to have a folder in a folder with the same name.

My Previous Code:

    foreach (string file in newZips) {

        FileInfo fileInfo = new FileInfo(file);
        string dirName = newPath + "\\" + fileInfo.Name.Substring(0, fileInfo.Name.Length - 4);
        Console.WriteLine(dirName);
        Directory.CreateDirectory(dirName);
        ZipFile.ExtractToDirectory(allZipsPath + "\\" + fileInfo.Name, dirName);
    }

Solution

  • Maybe this helps you:

    string path = @"C:\..\..\myFolder";
    if(!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }
    

    Thats how you can check a path if it contains the Folder you expect. And if not it creates that Folder!

    --- EDIT (if unknown zip-Name) ---

    string myPathToZip = @"C:\..\..\folderName";
    foreach (string file in Directory.GetFiles(myPathToZip, "*.zip", SearchOption.AllDirectories))
    { 
        //the current path of the zipFile (with the Name included)
        var path = new FileInfo(file.ToString());
    
        //The filename
        var filename = Path.GetFileName(file.ToString()).Replace(".zip", "");
    }