0

I want my application to search through the whole computer for a specific file, and open it. I tried:

var files = new List<string>();
foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady == true))
{
    files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, "Kalimba.mp3", SearchOption.AllDirectories));
}

Got error: No access C:\$Recycle.Bin\S-1-5-18.

Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
user2944342
  • 105
  • 2
  • 2
  • 10

1 Answers1

3

Well your DirectoryInfo.GetFiles method throws an UnauthorizedAccessException exception cause you don't have access to this hidden directory.

Correction: catch the exception.


UPDATE: as the comments say, you're getting all your files in a single GetFiles call, so catching the exception won't help. Slightly modify your code to manually get the list of directories, so you can catch and handle the exception for the specific directory you have not rights on.

See How to recursively list all the files in a directory in C#? for a complete example.

Community
  • 1
  • 1
ken2k
  • 48,145
  • 10
  • 116
  • 176
  • Just catching the exception won't do. The operation would stop. The directory should be skipped. – Mike Perrenoud Nov 13 '13 at 13:17
  • Catching the exception is not a solution since OP uses `SearchOption.AllDirectories`. Then it's likely that he won't find his file. He needs to use his own method to traverse all folders recursively to catch an exception at one folder or file instead of at the root-folder. – Tim Schmelter Nov 13 '13 at 13:17
  • I read the question too fast, you're both totally right. Edited the question. Thanks for pointing out the mistake. – ken2k Nov 13 '13 at 13:21