This question already has an answer here:
Directory.GetFiles method fails on the first encounter with a folder it has no access rights to.
The method throws an UnauthorizedAccessException (which can be caught) but by the time this is done, the method has already failed/terminated.
The code I am using is listed below:
try
{
// looks in stated directory and returns the path of all files found
getFiles = Directory.GetFiles(
@directoryToSearch,
filetype,
SearchOption.AllDirectories);
}
catch (UnauthorizedAccessException)
{
}
As far as I am aware, there is no way to check beforehand whether a certain folder has access rights defined.
In my example, I'm searching on a disk across a network and when I come across a root access only folder, my program fails.
The simplest version:
In order to gain control on the level that you want, you should probably probe one directory at a time, instead of a whole tree. The following method populates the given
IList<string>
with all files found in the directory tree, except those where the user doesn't have access:This is an enhancement to Malcolm's answer (http://stackoverflow.com/a/9831340/226181). This scans all logical drives for a file match pattern and ignores the directories that are not accessible.
I know this thread is old, but in case someone stumbles upon this and needs an answer, i got a recursive solution here:
It returns an
List<string>
containing the full path to all files that are in accessible directories below the given root-directory. Call it like this:So one result could be like this:
Hope it helps someone!
This is my solution for this problem. Simple and fail safe.
.Net 4's Directory.EnumerateFiles does work, but you've got to be careful how you evaluate the enumerable and do that part inside the try-catch block. The biggest issue is making sure you don't stop processing at the first exception (which I think answer https://stackoverflow.com/a/1393219/89584 above has this problem, please correct me if I'm wrong there).
The following works and gives you an Enumerable so you don't have to evaluate the entire file tree if you're looking for the first match, etc.
improvements to the above welcome.