UnauthorizedAccessException无法解析Directory.GetFiles失败 [英] UnauthorizedAccessException cannot resolve Directory.GetFiles failure

查看:137
本文介绍了UnauthorizedAccessException无法解析Directory.GetFiles失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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< string> ,但用户无法访问的文件除外:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆