Click here to Skip to main content
15,897,371 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to search a file in all drive and directories. Below is my code but when I try to SearchOption. TopDirectoryOnly it works but in AllDirectories it generate the exception (Hope there are some access denied directories.
Please help how to skip these directories or any other way …
C#
DriveInfo[] allDrive = DriveInfo.GetDrives();

foreach (DriveInfo d in allDrive)
{
    string b = d.Name.ToString();
     var filename = Directory.GetFiles(b, "*.doc*", SearchOption.AllDirectories);

        foreach (string a in filename)
        {
          listBox1.Items.Add(a.ToString());
          listBox1.Items.Add("Creation Time:"+System.IO.File.GetCreationTime(a.ToString()));
        }
}
Posted
Updated 20-Nov-15 23:41pm
v2
Comments
Richard MacCutchan 21-Nov-15 5:32am    
What exception, and where does it occur?
Adi tyagi 21-Nov-15 5:45am    
exp is when i am using SearchOption.AllDirectories : An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll

Additional information: Access to the path 'C:\$RECYCLE.BIN\S-1-5-18' is denied.

Richard MacCutchan 21-Nov-15 6:13am    
Then you need to catch the exception and ignore any directories that raise this exception.

1 solution

You can't use AllDirectories on the root folder without almost certainly getting access violations - unless you have full admin privileges, which is rather overkill for a simple file search!

Your only option is to use a recursive folder check inside a try...catch block, and check each folder on the drive individually, followed by its subfolders provided you have access to them.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900