Reputation: 544
I am trying to verify if a file exist in a c# console program. The only thing is that the file can have any name.
The only thing that I know is the file extension and there can only be one file of this extension. How can I verify if it exist and then use it whatever the name is?
Upvotes: 0
Views: 1485
Reputation: 74355
The problem with using Directory.GetFiles()
is that is walks the entire filesystem first, then returns all matches as an array. Even if the very first file examined is the one and only match, it still walks the entire filesystem from the specified root before returning the one match.
Instead, use EnumerateFiles()
to do a lazy walk, stopping when the first match is encountered, thus:
DirectoryInfo root = new DirectoryInfo( @"C:\" ) ;
string pattern = "*.DesiredFileExtension" ;
FileInfo desiredFile = root.EnumerateFiles( pattern , SearchOption.AllDirectories )
.First()
;
It will throw an exception if the file's not found. Use FirstOrDefault()
to get a null
value instead.
Upvotes: 4
Reputation: 43636
Something like this may work
if (Directory.GetFiles(path, "*.ext").Any())
{
var file = Directory.GetFiles(path, ".ext").First();
}
Upvotes: 1
Reputation: 5110
string extension = "txt";
string dir = @"C:\";
var file = Directory.GetFiles(dir, "*." + extension).FirstOrDefault();
if (file != null)
{
Console.WriteLine(file);
}
If the file does not exist directly under 'dir', you will need to use SearchOption.AllDirectories for Directory.GetFiles
Upvotes: 1
Reputation: 49985
Try the Directory.GetFiles static method:
var fileMatches = Directory.GetFiles("folder to start search in", "*.exe", SearchOption.AllDirectories);
if (fileMatches.Length == 1)
{
//my file was found
//fileMatches[0] contains the path to my file
}
Note that with the SearchOption enum you can specify just the current folder or to search recursively.
Upvotes: 3