First get your head around a simple recursive function like factorial
. For example:
int factorial(int number) {
if (number < 1)
return 1;
else
return factorial(number - 1) * number;
}
Basically, if we want to calculate factorial(5)
, then it's just:
factorial(5) * factorial(4) * factorial (3) * factorial(2) * factorial(1)
or more abstractly:
factorial(n) * factorial(n - 1) * factorial (n - 2) * ... * factorial (1)
So we make the function call itself with a diminishing value to compute the result.
The same applies do your problem above. If we want to get all the sub directories, then all we have to do is:
(1) List all the files in the current folder
(2) For the files that are directories, repeat step one.
In other words:
List<Folder> readAllFiles() {
List<Folder> folders = new List<Folder>();
readAllFilesRecursively("C:/", folders);
}
List<Folder> readAllFilesRecursively(String directory, List<Folder> folders) {
Folder currentDirectory = castTheStringToADirectorySomehow(directory);
// Add the current folder to the list.
folders.add(currentDirectory);
// ** HERE IS WHAT YOU'RE MISSING ** //
// Re-call the same function on the sub folder, passing in our list
// so that the subfolder items can be added to the list.
foreach (Folder subfolder in currentDirectory.subFolders()) {
readAllFilesRecursively(subFolder.pathString(), folders);
}
// Return the folder list.
return folders;
}
Edit:
So this works for me, but you'll have to change it to VB obviously. Also, I'm on a mac so you'll notice that the path format is a little different:
class Program {
public static void Main() {
List<FileInfo> files = new List<FileInfo> ();
AppendFilesFromDirectory (new DirectoryInfo("/Users/sircodesalot/Desktop/Dev"), files);
foreach (FileInfo file in files) {
Console.WriteLine (file.FullName);
}
}
public static void AppendFilesFromDirectory(DirectoryInfo currentFolder, List<FileInfo> files) {
foreach (FileInfo file in currentFolder.GetFiles()) {
files.Add(file);
}
// This if statement is unneccesary, but I'll add it for clarity
// to explain the concept of a base case. We don't really need it though
// since the 'foreach' statement won't execute if there aren't any items.
if (currentFolder.GetDirectories().Count() > 0) {
// Process the subfolders
foreach (DirectoryInfo subfolder in currentFolder.GetDirectories()) {
AppendFilesFromDirectory (subfolder, files);
}
}
}
}