Here I am writing an example which shows how
to get list of file names from a directory (including its subdirectories), and
also demonstrate how one can filter the list by extension.
Get all files from directory
To get all files from directory, method Directory.GetFiles returns string array with files names (full paths).
You can specify search
pattern, inside your directory. You can use wildcard specifiers in the search
pattern, e.g. ‘*.txt’ to select files with the extension or ‘a*’ to select
files beginning with letter ‘a’.
If you want to get files of its subdirectories
also then use parameter SearchOption.AllDirectories.
I have one directory(Folder)
named as Sandeep under D drive(ref. fig.1),
which have three files and one subdirectory Test Dir.
Test Dir also contains one file(ref. fig.2)
To get file names from the specified
directory, we need to use static method Directory.GetFiles
fig.1
Test Dir also contains one file(ref. fig.2)
fig.2
Get all files from directory
To get all files from directory, method Directory.GetFiles returns string array with files names (full paths).
String[]
files = System.IO.Directory.GetFiles(@"c:\Sandeep\");
// returned
files:
//
"D:\Sandeep\abc.txt"
//
"D:\Sandeep\Test_123.xls"
//
"D:\Sandeep\Test_1222.doc"
Get files from directory (with specified extension)
String[]
files = System.IO.Directory.GetFiles(@"c:\Sandeep\", "*.txt");
// returned
files:
//
"D:\Sandeep\abc.txt"
Get files from directory (including its
subdirectories)
String[]
files = System.IO.Directory.GetFiles(@"c:\Sandeep\", "*.doc",
System.IO.SearchOption.AllDirectories);
// returned
files:
//
"D:\Sandeep\Test_1222.doc"
//
"D:\Sandeep\Test Dir\Test423.doc"
Cheers!!!!
Comments
Post a Comment