Reputation: 17
this is my code below. I've already created a filter that searches for any all image file extensions but when my code runs the SearchOption.AllDirectories
appears to be trying to open a particular path instead of searching all my directories.
Anyone help me on where I've gone wrong here?
string[] filters = { "*.jpg", "*.jpeg", "*.png", "*.gif", "*.bmp" };
var directory = new DirectoryInfo(lblText.Text);
var files = new List<FileInfo>();
foreach (var filter in filters)
{
var results = directory.GetFiles(filter, SearchOption.AllDirectories);
files.AddRange(results);
}
Thanks for any help! :)
Upvotes: 0
Views: 11647
Reputation: 460038
I assume directory
is a DirectoryInfo
object and you're using this overload of GetFiles
. Then a FileInfo[]
is returned from the current directory matching the given search pattern and searching all subdirectories.
So the directory-path of the DirectoryInfo
is the root directory.
For example:
DirectoryInfo imageDir = new DirectoryInfo(@"c:\Images");
FileInfo[] allJPGImages = imageDir.GetFiles(".jpg", SearchOption.AllDirectories);
Edit according to your edit.
So the particular path is the Text
entered/shown in lblText
. Another way to get all files with these extensions:
string[] filters = { "*.jpg", "*.jpeg", "*.png", "*.gif", "*.bmp" };
List<FileInfo> files = filters
.SelectMany(filter => directory.EnumerateFiles(filter, System.IO.SearchOption.AllDirectories))
.ToList();
which does not need to load all files into memory until it starts processing. when you are working with many files and directories, EnumerateFiles
can be more efficient.
Upvotes: 2
Reputation: 557
I am not sure what filter is in your code, but here is a simple example to search a directory.
string path = "C:\\myFolder1\\myFolder2";
DirectoryInfo dir = new DirectoryInfo(path);
FileInfo[] files;
files = dir.GetFiles("*.*", SearchOption.AllDirectories);
Maybe your path is wrong? But the AllDirectories options begins at your specified path.
Upvotes: 0