递归调用会损坏我的数据吗?
我调用此函数来加载带有磁盘上目录列表的 TreeView。
private void LoadDirectories(string currentPath, TreeNodeCollection nodes)
{
DirectoryInfo directoryInfo = new DirectoryInfo(currentPath);
DirectoryInfo[] directories = directoryInfo.GetDirectories();
foreach (DirectoryInfo dir in directories)
{
if ((dir.Attributes & FileAttributes.System) != FileAttributes.System &&
(dir.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
{
TreeNode newNode = nodes.Add(dir.Name);
LoadDirectories(dir.FullName, newNode.Nodes);
}
}
}
如果我注释掉递归调用,我将获得树中的所有子目录。如果我不这样做,我就不会。有些目录丢失了。我不确定发生了什么事。
帮助?
斯科特
I'm calling this function to load a TreeView with a list of the directories on the disk.
private void LoadDirectories(string currentPath, TreeNodeCollection nodes)
{
DirectoryInfo directoryInfo = new DirectoryInfo(currentPath);
DirectoryInfo[] directories = directoryInfo.GetDirectories();
foreach (DirectoryInfo dir in directories)
{
if ((dir.Attributes & FileAttributes.System) != FileAttributes.System &&
(dir.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
{
TreeNode newNode = nodes.Add(dir.Name);
LoadDirectories(dir.FullName, newNode.Nodes);
}
}
}
If I comment out the recursive call I get all of the subdirectories in the tree. If I don't I don't. Some directories are missing. I'm not sure what is going on.
Help?
Scott
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用这个示例代码它工作得很好。我建议您以此为起点。
Using this example code it works just fine. I recommend you use this as a starting point.
事实证明问题根本不在于递归调用。问题在于,如果当前用户无权访问所请求的目录,则
GetDirectories
调用会引发AccessDenied
异常。我只是将适当的调用包装在 try/catch 块中,一切都很好。
感谢您对混沌的帮助!
It turns out the problem wasn't with the recursive call at all. The problem was that the
GetDirectories
call was throwing anAccessDenied
exception if the current user didn't have access to the requested directory.I simply wrapped the appropriate calls in a try/catch block and all is well.
Thanks for your help Chaos!