UnauthorizedAccessException 无法解决 Directory.GetFiles 失败 [英] UnauthorizedAccessException cannot resolve Directory.GetFiles failure
问题描述
Directory.GetFiles 方法 在第一次遇到它没有访问权限的文件夹.
Directory.GetFiles method fails on the first encounter with a folder it has no access rights to.
该方法抛出一个 UnauthorizedAccessException(可以被捕获),但在完成时,该方法已经失败/终止.
The method throws an UnauthorizedAccessException (which can be caught) but by the time this is done, the method has already failed/terminated.
我使用的代码如下:
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.
推荐答案
为了获得所需级别的控制权,您可能应该一次探测一个目录,而不是整个树.以下方法使用目录树中找到的所有文件填充给定的 IList
,用户无权访问的文件除外:
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:
// using System.Linq
private static void AddFiles(string path, IList<string> files)
{
try
{
Directory.GetFiles(path)
.ToList()
.ForEach(s => files.Add(s));
Directory.GetDirectories(path)
.ToList()
.ForEach(s => AddFiles(s, files));
}
catch (UnauthorizedAccessException ex)
{
// ok, so we are not allowed to dig into that directory. Move on.
}
}
这篇关于UnauthorizedAccessException 无法解决 Directory.GetFiles 失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!