c# - UnauthorizedAccessException 无法解决 Directory.GetFiles 失败

标签 c# exception-handling unauthorized getfiles

<分区>

Directory.GetFiles method第一次遇到它没有访问权限的文件夹时失败。

该方法抛出一个 UnauthorizedAccessException(可以被捕获),但在完成时,该方法已经失败/终止。

我使用的代码如下:

try
{
    // looks in stated directory and returns the path of all files found                
    getFiles = Directory.GetFiles(
        @directoryToSearch, 
        filetype, 
        SearchOption.AllDirectories);             
}
catch (UnauthorizedAccessException) 
{ 
}

据我所知,没有办法事先检查某个文件夹是否定义了访问权限。

在我的示例中,我正在通过网络搜索磁盘,当我遇到一个仅限根访问的文件夹时,我的程序失败了。

最佳答案

为了获得所需级别的控制,您可能应该一次探测一个目录,而不是整个树。以下方法填充给定的 IList<string>在目录树中找到的所有文件,用户无权访问的文件除外:

// 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.
    }
}

关于c# - UnauthorizedAccessException 无法解决 Directory.GetFiles 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1393178/

相关文章:

c# - 有条件地编译整个命名空间 - C#

c# - Thread.Sleep(2500) 与 Task.Delay(2500).Wait()

java - Java 异常处理的最佳实践

python - 当前异常上下文掩盖了先前的错误

非顺序任务中的 Java 异常处理(模式/良好实践)

c# - 无法将随机生成的 int 从 Controller 写入 DB

c# - Selenium force driver.Quit 忽略 "asking to leave"对话框

asp.net-mvc - Asp.net Mvc自定义机制来处理未经授权的请求

javascript - 未经授权的域名屏蔽

java - Spring Security - 尽管允许所有请求但未经授权