In my previous tutorials, I’d explained how to upload and download files in asp.net, get folder files list and export to csv or excel in asp.net and other more cracking tutorials on Files, JavaScript, jQuery in Asp.net with an example code.
Now here in this tutorial, I’ll explain how to find or get files list from directory or folder (including subdirectories, file name with extension). I’ve also provided an example to filter files list with certain file extensions.
To get list of file names from the specified directory or folder, we need to use static method Directory.Get Files included in System.IO namespace. This method returns the names of files (including their full path) from the specified directory structure.
Get Files List From Directory
It’ll return all the files (including full path) from the specified directory:
C#
string[] allFiles = Directory.GetFiles(baseDirectory);
Vb.net
Dim allFiles As String() = Directory.GetFiles(baseDirectory)
Get Files List From Directory With Filtering File Extension
It’ll return all the files (including full path) from the specified directory with specified file extension:
C#
string[] allFiles = Directory.GetFiles(baseDirectory, “*.png”);
Vb.net
Dim allFiles As String() = Directory.GetFiles(baseDirectory, “*.png”)
After executing the above statements, it’ll filter out specified directory and return list of files with “.png” extension.
Get Files List From Directory Including Sub-directory
It’ll return all the files (including full path) from the specified directory as well as all sub-directories with specified file extension:
C#
string[] allFiles = Directory.GetFiles(baseDirectory, “*.png”, SearchOption.AllDirectories);
Vb.net
Dim allFiles As String() = Directory.GetFiles(baseDirectory, “*.png”, SearchOption.AllDirectories)
Recursively Traverse Directory Structure
Following is the simple example that get files list from directory as well as it’s sub-directories and write each files in console:
C#
string[] allFiles = Directory.GetFiles(baseDirectory, “*.*”, SearchOption.AllDirectories);
foreach (var file in allFiles)
{
Console.WriteLine(file);
}
Vb.net
Dim allFiles As String() = Directory.GetFiles(baseDirectory, “*.*”, SearchOption.AllDirectories)
For Each file In allFiles
Console.WriteLine(file)
Next
That’s it, now you’ll be able to get files list from directory or specified folder with it’s sub-folders recursively without any trouble.