EnumerateFiles on disk using LINQ to skip the recycle bin

Now I am writing a small method that extracts all the full file names of a given input string and a given drive. My method is as follows:

private IEnumerable<string> FindOccurences(string searchQuery, DriveInfo drive)
{
    return drive.RootDirectory
        .EnumerateFiles("*" + searchQuery + "*", SearchOption.AllDirectories)
        .Where(file => !file.FullName.Contains("RECYCLE"))
        .Select(file => file.FullName);
}

While everything works fine on disks that don’t have a recycle bin, mine C:\and D:\Directory raise UnauthorisedAccessExceptionwhen listing through files and to Recycle Bin . The same problem is explained and used in this section , but does not use LINQ to solve it.

I was hoping that with LINQ, a solution would appear to skip the cart and go to other directories. Is it possible? As you can see, I already tried to do something in the form of a name check, but this did not solve my problem.

(How) can I skip the cart using LINQ?

: C:\Directory ( ): C:\$Recycle.Bin

+4
1

, .

GetFiles, EnumerateFiles : .

, , . , , Where.

Recycle Bin , , , , .

, , ( try/catch).

0

Source: https://habr.com/ru/post/1545357/


All Articles