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.
在code我现在用的就是如下:
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.
在我的例子,我在寻找一个磁盘上在网络上,当我遇到一个root权限的文件夹,我的计划失败。
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屋!