views:

787

answers:

3

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?

Any help is wonderful :)

+4  A: 

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));
     }
Hamish Smith
Almost - you need to add in the SearchOption
Reed Copsey
what happens when you dont have access to the give directory...say "Documents and Settings" :)
Stan R.
yeah, some exception handling will be necessary - the fragment will fail on most machines because the floppy drive isn't ready. It shows the syntax for the GetFiles method though, which is what is needed.
Hamish Smith
@Hamish: you could do this to quickly handle the floppy issue. DriveInfo.GetDrives().Where(x => x.IsReady == true)
Stan R.
A: 

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.

lc
A: 

Hi programmers, if someone have a solution please upload it. :-)

Andrew