DriveInfo.GetDirectories throws UnauthorizedAccessException

Consider the following line of code

DirectoryInfo Dir = DriveInfo.GetDrives()[1].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)
{

if(Dir.Exists)
{
FileInfo[] files;
try
{
files = Dir.GetFiles(file,SearchOption.AllDirectories) ;
files = Dir.GetFiles(file,SearchOption.TopDirectoryOnly);
if(files.Length != 0)
{
foreach(FileInfo res in files)
Console.WriteLine("Found:{0}",res.FullName);
}
else
foreach(DirectoryInfo _dir in Dir.GetDirectories())
SearchFile(file,_dir);
}
catch(UnauthorizedAccessException ex)
{
Console.WriteLine(ex.Message);
}
}
[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 ....

Comments

Popular posts from this blog

Khuda Karay K Meri Arz -e- Pak Par Utray

میرے بعد بہت سناٹا ہوگا

ME as Author for KMB!!!