Recursively scan directories for files using a Stack collection to store results.
Recursive files. A program needs to recurse through all directories. It starts at a certain point. It then lists all the file paths in those directories. We can use an efficient and bug-free VB.NET Function for this purpose.FunctionFile
Example. First, this is the code for the VB.NET Function that traverses through all subdirectories and then all further subdirectories. It returns a List(Of String), which is often used for file paths.Path
Stack: It uses Stack to build up a list of paths it needs to process. It then processes each directory path in the stack, adding all the files each time.
Main: The Main sub here shows how to call FileHelper.GetFilesRecursive and specify a path string.
Tip: The path string must specify an absolute path, or one relative to the program. Here, we specify a C:\ path on my computer.
VB.NET program that recurses directories
''' This class contains directory helper method(s).
Public Class FileHelper
''' This method starts at the specified directory.
''' It traverses all subdirectories.
''' It returns a List of those directories.
Public Shared Function GetFilesRecursive(ByVal initial As String) As List(Of String)
' This list stores the results.
Dim result As New List(Of String)
' This stack stores the directories to process.
Dim stack As New Stack(Of String)
' Add the initial directory
' Continue processing for each stacked directory
Do While (stack.Count > 0)
' Get top directory string
Dim dir As String = stack.Pop
' Add all immediate file paths
' Loop through all subdirectories and add them to the stack.
Dim directoryName As String
For Each directoryName In Directory.GetDirectories(dir)
Catch ex As Exception
' Return the list
''' Entry point that shows usage of recursive directory function.
' Get recursive List of all files starting in this directory.
Dim list As List(Of String) = FileHelper.GetFilesRecursive("C:\Users\Sam\Documents\Perls")
' Loop through and display each path.
For Each path In list
' Write total number of paths found.
Output. The output of the program on my computer is a list of 677 file paths. Each path is fully specified and absolute. They are ordered alphabetically. The sample next shows three of the first several lines printed.
Note: I checked the directory in Windows Explorer by right-clicking on the folder and selecting Properties.
And: The dialog shows that there are 677 files in the folder. Further inspection shows all file paths are accurate.
Summary. Here we saw a powerful and efficient recursive directory and subdirectory traversing function. It works reliably in programs. It is tested. The function provides accurate results.
Review: It demonstrates an excellent use of Stack and List. It is highly useful in many projects.