简体   繁体   中英

Find a file within all possible folders?

I was wondering how I could use c# to find a specific file (example cheese.exe) within all possible directories? And then store the path to the directory it found it in?

This code fragment retrieves a list of all logical drives on the machine and then searches all folders on the drive for files that match the filename "Cheese.exe". Once the loop has completed, the List "files" contains the

     var files = new List<string>();
     //@Stan R. suggested an improvement to handle floppy drives...
     //foreach (DriveInfo d in DriveInfo.GetDrives())
     foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady == true))
     {
        files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, "Cheese.exe", SearchOption.AllDirectories));
     }

If you want to know a little more about the mechanics of searching multiple directories, Googling revealed this post . It has a good solution and explanation of recursing through directories yourself. You can change the filespec in Directory.GetFiles to match your search string and probably use it as is.

The link is unfortunately dead now, but in a nutshell the solution basically boils down to:

string[] files = Directory.GetFiles("C:\\Starting\\Path\\For\\Search\\",
    "cheese.exe",
    SearchOption.AllDirectories);

Note the filespec (second parameter) accepts wildcards, so you can also search for " .exe" or even " .*" to list all files recursively.

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