简体   繁体   中英

find a file name knowing only the extension name

I am trying to verify if a file exist in ac# 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:

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.

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.

Something like this may work

if (Directory.GetFiles(path, "*.ext").Any())
{
   var file = Directory.GetFiles(path, ".ext").First();
}
  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM