为什么尝试在递归函数C#中捕获错误

时间:2015-06-18 04:57:45

标签: c# treeview

我创建了一个用于使用目标目录填充树视图的函数。但是,当我尝试实现和错误检查以跳过可能具有文件夹权限限制的文件夹时,我收到错误。为什么我会收到此错误以及如何解决?

提前谢谢。

using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace directoryBrowser
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            ListDirectory(treeView1, @"C:\Windows");
        }

        public void ListDirectory(TreeView treeView, string path)
        {
            treeView.Nodes.Clear();
            var rootDirectoryInfo = new DirectoryInfo(path);
            treeView.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo));
        }

        public static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
        {
            //try
            //{
                var directoryNode = new TreeNode(directoryInfo.Name);

                foreach (var directory in directoryInfo.GetDirectories())
                {
                    directoryNode.Nodes.Add(CreateDirectoryNode(directory));
                }
                foreach (var file in directoryInfo.GetFiles())
                {
                    directoryNode.Nodes.Add(new TreeNode(file.Name));
                }
                return directoryNode;
            //}
            //catch (UnauthorizedAccessException) { }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您正在回答自己的问题。您收到错误,因为运行此功能的用户帐户无权访问某些文件夹。

然后你应该在for循环中应用一个try / catch语句,所以如果你得到这个异常,你的函数将继续为以下文件夹运行。

public static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
    {
        var directoryNode = new TreeNode(directoryInfo.Name);

        foreach (var directory in directoryInfo.GetDirectories())
        {
             //try
            {
                directoryNode.Nodes.Add(CreateDirectoryNode(directory));
            } catch {
                // cannot access directory
            }
        }
        foreach (var file in directoryInfo.GetFiles())
            {
                directoryNode.Nodes.Add(new TreeNode(file.Name));
            }
            return directoryNode;
        }