我正在填充 TreeView 控件,c# visual studio 8,使用此代码:
private TreeNode TraverseDirectory(string path)
{
TreeNode result = new TreeNode(path);
foreach (var subdirectory in Directory.GetDirectories(path))
{
result.Nodes.Add(TraverseDirectory(subdirectory));
}
return result;
}
问题是,如果我点击 c:/驱动器,我会在我没有权限读取的目录上收到错误消息。我的问题是,如何避免显示那些我没有权限的目录?我将如何对此进行测试,然后告诉应用程序忽略它们?
谢谢 R。
最佳答案
对于一个简单的方法:
TreeNode result;
try {
string[] subdirs = Directory.GetDirectories(path);
result = new TreeNode(path);
foreach(string subdir in subdirs) {
TreeNode child = TraverseDirectory(subdir);
if(child != null) { result.Nodes.Add(child); }
}
return result;
} catch (FindTheSpecificException) {
// ignore dir
result = null;
}
return result;
个人我会尝试进行某种延迟加载,但 IIRC 这涉及使用标准 TreeView
添加虚拟节点。
关于C# 填充 treeview 并在我无权读取的目录上出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2130478/