Question

What i am trying to do is create a section of C# code that is able to take a .zip file, extract it, and for the sake of this example, find a folder i shall refer to as 'Target', this target folder will have a different name for each package, but the structure of the contents will be uniform. The package name does not derive the target folder name.

The structure of the .zip file can be either of the three:

.\Thing.zip\GameData\Target\

.\Thing.zip\ThingCorp\GameData\Target\

.\Thing.zip\Target\

Now i have the extraction of .zip files working, i just need a way to reliably find the Target folder, is there a way of checking if a folder exists within a directory and its subdirectories?

Was it helpful?

Solution

What about

Directory.EnumerateDirectories(pathHere);

?

This will yield an IEnumerable with all directories from the given path which you may use... To make sure a directory exists before you pass it along, make sure you call

Directory.Exists(pathToVerify);

OTHER TIPS

For relative search you can use the Directory.GetDirectories() method to find all folders that contain e.g. 'Target', started in your root-directory and searching all subfolders:

var dirs = Directory.GetDirectories(yourSearchRootDir, "*Target*", SearchOption.AllDirectories);

So when dirs contains a directory you are searching for, the target-directory exists.

Once you have your .zip/.rar extracted you can use

System.IO.Directory.Exists(string path);

If however you want to verify the existence of this directory before extracting, and if you are okay with using external libraries. You could use the DotNetZip library.

You can create a Ionic.Zip.ZipFile object from a stream in memory or directly from the files on the drive.

ZipFile objects have a method called ContainsEntry

using (Ionic.Zip.ZipFile myZip = ZipFile.Read("MyArchive.zip"))
{
    if(myZip.ContainsEntry(string path))
    {
        //Something
    }
}

This way you can know for certain that the directory you want exists before extracting

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top