递归调用破坏了我的数据?

时间:2010-08-02 02:34:09

标签: c# recursion

我正在调用此函数来加载带有磁盘上目录列表的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);
        }
    }
}

如果我注释掉递归调用,我会得到树中的所有子目录。如果我不这样做。有些目录丢失了。我不确定发生了什么。

帮助?

斯科特

2 个答案:

答案 0 :(得分:0)

使用此示例代码,它可以正常工作。我建议你以此为出发点。

static void Main(string[] args)
{
    var n = LoadDirectory(@"E:\Share");
    Console.WriteLine(n.ToString());
    Console.ReadLine();
}

private static Node LoadDirectory(string path)
{
    var n = new Node() { Name = path };
    LoadDirectories(path, n);
    return n;
}

private static void LoadDirectories(string currentPath, Node node)
{
    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)
        {
            var n = new Node() { Name = dir.Name };
            node.Children.Add(n);
            LoadDirectories(dir.FullName, n);
        }
    }
}

private class Node
{
    public List<Node> Children = new List<Node>();
    public string Name;

    public override string ToString()
    {
        return ToString(1);
    }

    public string ToString(int depth)
    {
        if (Children.Count == 0)
        {
            return Name;
        }
        var sb = new StringBuilder(Name);
        foreach (var n in Children)
        {
            sb.AppendLine();
            sb.Append("".PadLeft(depth, '\t') + n.ToString(depth + 1));
        }
        return sb.ToString();
    }
}

答案 1 :(得分:0)

事实证明问题不在于递归调用。问题是,如果当前用户无权访问请求的目录,则GetDirectories调用会抛出AccessDenied异常。

我只是将相应的调用包装在try / catch块中,一切都很好。

感谢您的帮助Chaos!