3

I have a main folder which contains many sub directories. Inside each sub directory, there are many sub directories.

Does anyone knows how can I loop through the many sub directories in each sub directory?

This is my codes currently:

if (Directory.Exists(MainDirectory))
{
    foreach (DirectoryInfo SubDir in new DirectoryInfo(MainDirectory).GetDirectories())
    {
        foreach (FileInfo Image in SubDir.GetFiles())
        {
            Image.Delete();
        }
        SubDir.Delete(true);            
    }
    Directory.Delete(MainDirectory, true);
}

My current codes will only loop through the images from each subdirectory from the main directory.

Please help me on this.

1 Answer 1

4

You can use the Directory SearchOption.AllDirectories or you can use recursive call for it, whichever is appropriate.

If what you really interested in are files rather than to enter the sub-directories themselves, the method that you can use is Directory.GetFiles, something like this:

string[] files = Directory.GetFiles(folderpath, "*", SearchOption.AllDirectories); //"*" denotes all file format

the return is string[] which contains all filepaths in the given folderpath including those which are in the sub-directories.

You can change the SearchPattern ("*" in the example) to suit the file search pattern (formats) which you need.

If you really need to enter the sub-directory however, you can create recursive calls and in the call, you can check if the directory has further (deeper) folder by using DirectoryInfo.GetDirectories()

Sign up to request clarification or add additional context in comments.

2 Comments

Nicely explained +10.
Welcome, Hope the path is not troubling you anymore.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.