DriveInfo.GetDirectories throws UnauthorizedAccessException
Consider the following line of code
DirectoryInfo Dir = DriveInfo.GetDrives().RootDirectory.GetDirectories();
FileInfo files = Dir.GetFiles("anyfile.txt",SearchOption.AllDirectories) ;
First line will return RootDirectory of C drive (usually C drive is the second drive, after A or floppy drive). Second line uses GetFiles method that will apply on Root Directory of C. GetFiles takes two arguments, one is string search pattern where second is an enumeration that says either to search in all directories or only in top level directories.
But this code will throw an error if you don't have appropriate right for any folder of C Drive .... for example on Windows XP with multiple users, you should not have rights to see files of other users .... in result the search interrupted and unsuccessful.
To avoid such problem, we can use recursive function... that recursive function can catch UnauthorizedAccessException ... can we not in above Code?? Yes we can, but as it terminate whole search instead of terminating search for victim directory.
static void SearchFile(string file, DirectoryInfo Dir)
files = Dir.GetFiles(file,SearchOption.AllDirectories) ;
files = Dir.GetFiles(file,SearchOption.TopDirectoryOnly);
if(files.Length != 0)
foreach(FileInfo res in files)
foreach(DirectoryInfo _dir in Dir.GetDirectories())
[I am sorry, Windows Live Writter does not allow to format it properly]
This recursive function search for file only in top level directories, and then call recursively for each directories found in directory. In case, there is any directory/file you don't heave rights to access... it will skip only that directory and search will continue ....