4

I am in the process of writing a small method which retrieves all full filenames of a given input string and a given drive. My method 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 drives that do not have a Recycle Bin, my C:\ and D:\ Directoryraise UnauthorisedAccessException when enumerating through the files and into the Recycle Bin. This same problem is explained and used in this topic, but does not use LINQ to solve it.

I was hoping there would be a solution using LINQ to skip over the Recycle Bin and move on to the other directories. Is this possible? As you can see I already attempted something in the form of checking for name, but this did not solve my problem.

(How) can I skip over the Recycle Bin using LINQ?

Edit: I actually found an occurance in my C:\ Directory (OS Directory) as well: C:\$Recycle.Bin

Community
  • 1
  • 1
Matthijs
  • 3,162
  • 4
  • 25
  • 46
  • Interesting. I never assumed the recycle bin to be an actual directory, rather just a constructed list of "deleted" items. – Flater Jun 20 '14 at 11:53
  • @Flater From Raymond Chen's awesome blog : "How can I tell that a directory is really a recycle bin?" http://blogs.msdn.com/b/oldnewthing/archive/2008/09/18/8956382.aspx – Jason Evans Jun 20 '14 at 12:29

1 Answers1

0

I'm afraid you can't.

Unlike GetFiles, EnumerateFiles doesn't load the whole list of results in memory: you can enumerate results before the end of the search.

However, it'll always ask for permissions on the directory currently being searched before returning any result for that specific directory. This means it'll throw the exception before the Where clause is checked.

As a side note, not only Recycle Bin will throw an exception, but all other directories the user that run your process doesn't have access to.

You should go for the solution you found that enumerates files and directories separately (with a try/catch).

ken2k
  • 48,145
  • 10
  • 116
  • 176