FyreeW FyreeW - 3 months ago 18
C# Question

Stack overflow when creating TreeView

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?

Answer

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.