Need to search the directory/sub-directories to find a file, would prefer it to stop once it has found one.
Is this a feature built into DirectoryInfo.GetFiles that I am missing, or should I be using something else (self-implemented recursive search)?
Use DirectoryInfo.EnumerateFiles()
instead which is lazily returning the files (as opposed to GetFiles
which is bringing the full file list into memory first) - you can add FirstOrDefault()
to achieve what you want:
var firstTextFile = new DirectoryInfo(someDirectory).EnumerateFiles("*.txt")
.FirstOrDefault();
From MSDN:
The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of FileInfo objects before the whole collection is returned; when you use GetFiles, you must wait for the whole array of FileInfo objects to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.
(DirectoryInfo.EnumerateFiles
requires .NET 4.0)