DirectoryInfo.GetFiles()错误:System.UnathorizedAccessException

时间:2016-05-18 08:55:08

标签: c# exception authorization

请帮帮我!我有个问题。 代码:

...    
currentDirectory = new DirectoryInfo(absoluteCurrentPath);
FileInfo[] allFiles = currentDirectory.GetFiles("*", SearchOption.AllDirectories);
model.AllFiles = new List<MyFile>();
foreach (var f in allFiles)
{

    model.AllFiles.Add(new MyFile(f.Name, f.FullName, Utilites.ConvertBytesToMegabytes(f.Length)));
}

DirectoryInfo CurrentDirectory = "C:\\"或等于具有系统文件的其他目录时,则错误除外:System.UnathorizedAccessException。 当我接受一个块try-catch时,它只跳过GetFiles()。 如何获取所有文件并仅跳过系统文件或获取所有文件而不删除文件? 谢谢!

1 个答案:

答案 0 :(得分:2)

我之前写过一种方法:

public static IEnumerable<FileInfo> EnumerateFiles(string path, string searchPattern = null)
{
    searchPattern = searchPattern ?? "*";

    var queue = new Queue<string>();

    queue.Enqueue(path);

    do
    {
        path = queue.Dequeue();

        foreach (var file in SafeEnumerateFiles(path, searchPattern))
        {
            yield return new FileInfo(file);
        }

        foreach (var directory in SafeEnumerateDirectories(path))
        {
            queue.Enqueue(directory);
        }
    }
    while (queue.Any());
}

static IEnumerable<string> SafeEnumerateFiles(string path, string searchPattern)
{
    try
    {
        return Directory.EnumerateFiles(path, searchPattern);
    }
    catch (DirectoryNotFoundException) { }
    catch (SecurityException) { }
    catch (UnauthorizedAccessException) { }

    return Enumerable.Empty<string>();
}

static IEnumerable<string> SafeEnumerateDirectories(string path)
{
    try
    {
        return Directory.EnumerateDirectories(path);
    }
    catch (DirectoryNotFoundException) { }
    catch (SecurityException) { }
    catch (UnauthorizedAccessException) { }

    return Enumerable.Empty<string>();
}

该方法会跳过您没有权限的文件夹。