开发者

Recursive call is corrupting my data?

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);
    Directory开发者_C百科Info[] 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


Using this example code it works just fine. I recommend you use this as a starting point.

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();
    }
}


It turns out the problem wasn't with the recursive call at all. The problem was that the GetDirectories call was throwing an AccessDenied 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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜