Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search all directories in all drives for .txt files?

Tags:

c#

I am using this code to search all directories in all drives to search for all .txt files:

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

but in running I am having this error: enter image description here

How to resolv it?

Thank you.

like image 900
bbb Avatar asked Mar 24 '23 04:03

bbb


1 Answers

This is simply a permissions problem. Use a try/catch block. Some of the folders on your disk including RecycleBin folders are not accessible to unprivileged code.

public List<string> Search()
{
    var files = new List<string>();
    foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady))
    {
        try
        {
            files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, "*.txt", SearchOption.AllDirectories));
        }
        catch(Exception e)
        {
            Logger.Log(e.Message); // Log it and move on
        }
    }

    return files;
}

Also note that using Directory.GetFiles with AllDirectories option has an inherent problem that it will fail if ANY of the folders in the entire drive is not accessible, and thus you'll not get any files for that drive in your results. The solution is to do manual recursion. An excellent example of that approach is available in this SO question.

like image 128
dotNET Avatar answered Apr 26 '23 21:04

dotNET