0
public static TreeNode MakeTreeFromPaths(List<string> paths, string rootNodeName = "E:\\", char separator = '\\')
{
    var rootNode = new TreeNode(rootNodeName);
    foreach (var path in paths.Where(x => !string.IsNullOrEmpty(x.Trim())))
    {
        var currentNode = rootNode;
        var pathItems = path.Split(separator);
        foreach (var item in pathItems)
        {
            var tmp = currentNode.Nodes.Cast<TreeNode>().Where(x => x.Text.Equals(item));
            currentNode = tmp.Count() > 0 ? tmp.Single() : currentNode.Nodes.Add(item);
        }
    }
    return rootNode;
}

This function can populate a treeview with a given list of file paths. But there is a problem, It will create a root node named rootNodeName and then will add other child nodes. How can I avoid given rootNodeName? I do not need any extra root node which is creating with this function.

1 Answer 1

1

I assume that you are putting that TreeNode into a TreeView at some point, like this:

treeView.Nodes.Add(MakeTreeFromPaths(pathList));

Instead of adding that root node, you could add all its children, like this:

foreach(var node in MakeTreeFromPaths(pathList).Nodes)
{
    treeView.Nodes.Add(node);
}

This is not very beautiful though. It would be even nicer if you would take the TreeView as parameter and populate it directly or if you would return a list of nodes instead.

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

Comments

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.