Search code examples
c#directorygetdirectories

Get a list of the sub folders under a directory


Ok so this is my issue currently:

This is my main:

//System prompts user the type of archiving which will direct to the correct directory to set as root
Console.WriteLine("Enter the type of archiving you would like to do?");
string archivetype = Console.ReadLine(); 

//function that identifies which candidates to archive
Archive(archivetype, 20, 20);

//keep the application in debug mode
Console.ReadKey();

The archive method:

//Archive method determines which directory to search in and how many versions to archive
static void Archive(string archivetype, int pversion, int version)
{
    //regex pattern to get folder names of the type #.#.#.#/#. something
    Regex reg = new Regex(@"\d+(\.\d+)+");
    //setting where to start looking
    DirectoryInfo root = new           DirectoryInfo(@"C:\Users\jphillips\Desktop\test\parent\ACE-3_0");
    var dirs = new List<DirectoryInfo>();
    //i want to make a recursive call to all the folders in my root directory to obtain all the folders with the regex pattern above that are not empty and do not have 3 files inside
    WalkDirectoryTree(root);      
}

finally walk directorytree method

//so im using the walk directory tree on the microsoft website i need a way to have a sort of a global array to keep adding the directories that fit through the patterns mentioned above without resetting itself after each walkdirectorytree call
static void WalkDirectoryTree(System.IO.DirectoryInfo root)
{
    DirectoryInfo[] subDirs = null;

    // Now find all the subdirectories under this root directory.
    subDirs = root.GetDirectories();

    foreach (DirectoryInfo dir in subDirs)
    {
        //dirs is not global so it doesnt work here and i believe if i put a local array that it will reset itself everytime
        dirs = root.GetDirectories("*", SearchOption.TopDirectoryOnly).Where(d => reg.IsMatch(d.Name)).ToList();
        if()
        WalkDirectoryTree(dir);
    }
}

so im really lost at this point I want to able to call walkdirectorytree to go through all my folders and subfolders of my directory recursevely to extrract the paths that have the regex pattern and that are not empty and do not have 3 files inside tp give me a list of these folders paths.


Solution

  • You can get all the folders and subfolders in a single call with this overload of GetDirectories.

    You pass in a search string - but not a regex unfortunately and SearchOption.AllDirectories as the second argument. You can then pass the results through your regex to find the ones you are interested in.