0

I am getting a stack overflow, when I try to create a Tree View using WinForms.

private void createFeatureTree()
{
    FeatureTree.Nodes.Clear();
    FeatureTree.Nodes.Add(createTreeNode(new DirectoryInfo(starting directory path)));
}

private TreeNode createTreeNode(DirectoryInfo directory)
{
   var directoryNode = new TreeNode(directory.Name);
   foreach (var dir in directory.GetDirectories())
   {
       directoryNode.Nodes.Add(createTreeNode(directory));
   }

   foreach (var file in directory.GetFiles())
   {
       directoryNode.Nodes.Add(new TreeNode(file.Name));
   }

   return directoryNode;
}

createFeatureTree() is called on its own thread on the startup. How come I am getting a stack overflow error? Is there a limit to the amount of nodes that the TreeView can store?

1
  • 4
    I guess you mean directoryNode.Nodes.Add(createTreeNode(**dir**)); Commented Sep 6, 2016 at 21:55

1 Answer 1

2

Change a call

directoryNode.Nodes.Add(createTreeNode(directory));

to:

directoryNode.Nodes.Add(createTreeNode(dir));

And it should work. The reason you are getting "StackOverflowException" is that you always call createTreeNode method on directory variable passed in, not on its subdirectories (which, eventually, there would be none when you are at the leaf level).

Basicaly, if you pass in "C:\", you constantly call createTreeNode on "C:\" and it never ends.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, makes sense. Did not realize I had the original directory in there instead of the contained ones. Thank you for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.