当 Directory.GetFiles() 被拒绝访问时忽略文件夹/文件 [英] Ignore folders/files when Directory.GetFiles() is denied access

查看:42
本文介绍了当 Directory.GetFiles() 被拒绝访问时忽略文件夹/文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试显示在所选目录(以及可选的任何子目录)中找到的所有文件的列表.我遇到的问题是,当 GetFiles() 方法遇到它无法访问的文件夹时,它会引发异常并停止进程.

I am trying to display a list of all files found in the selected directory (and optionally any subdirectories). The problem I am having is that when the GetFiles() method comes across a folder that it cannot access, it throws an exception and the process stops.

如何忽略此异常(并忽略受保护的文件夹/文件)并继续将可访问文件添加到列表中?

How do I ignore this exception (and ignore the protected folder/file) and continue adding accessible files to the list?

try
{
    if (cbSubFolders.Checked == false)
    {
        string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
        foreach (string fileName in files)
            ProcessFile(fileName);
    }
    else
    {
        string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories);
        foreach (string fileName in files)
            ProcessFile(fileName);
    }
    lblNumberOfFilesDisplay.Enabled = true;
}
catch (UnauthorizedAccessException) { }
finally {}

推荐答案

您将不得不手动执行递归;不要使用 AllDirectories - 一次查看一个文件夹,然后尝试从子目录中获取文件.未经测试,但类似于以下内容(注意使用委托而不是构建数组):

You will have to do the recursion manually; don't use AllDirectories - look one folder at a time, then try getting the files from sub-dirs. Untested, but something like below (note uses a delegate rather than building an array):

using System;
using System.IO;
static class Program
{
    static void Main()
    {
        string path = ""; // TODO
        ApplyAllFiles(path, ProcessFile);
    }
    static void ProcessFile(string path) {/* ... */}
    static void ApplyAllFiles(string folder, Action<string> fileAction)
    {
        foreach (string file in Directory.GetFiles(folder))
        {
            fileAction(file);
        }
        foreach (string subDir in Directory.GetDirectories(folder))
        {
            try
            {
                ApplyAllFiles(subDir, fileAction);
            }
            catch
            {
                // swallow, log, whatever
            }
        }
    }
}

这篇关于当 Directory.GetFiles() 被拒绝访问时忽略文件夹/文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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