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?
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:It will throw an exception if the file’s not found. Use
FirstOrDefault()to get anullvalue instead.