Search code examples
c#.netwinformstreeviewtreenode

Arrange TreeView by getting file paths?


I have this code:

    public void AddNode(string Node)
    {
        try
        {
            treeView.Nodes.Add(Node);
            treeView.Refresh();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

Very simple as you see, this method gets file path. like C:\Windows\notepad.exe

Now i want the TreeView to show it like FileSystem..

-C:\
    +Windows

And if i click the '+' it gets like this:

-C:\
    -Windows
       notepad.exe

Here is what i get now from sending theses pathes to the method above:

TreeView current look

How can i do that it will arrange the nodes?


Solution

  • If I were you, I would split the input string onto substrings, using the string.Split method and then search for the right node to insert the relevant part of a node. I mean, that before adding a node, you should check whether node C:\ and its child node (Windows) exist.

    Here is my code:

    ...
                AddString(@"C:\Windows\Notepad.exe");
                AddString(@"C:\Windows\TestFolder\test.exe");
                AddString(@"C:\Program Files");
                AddString(@"C:\Program Files\Microsoft");
                AddString(@"C:\test.exe");
    ...
    
            private void AddString(string name) {
                string[] names = name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                TreeNode node = null;
                for(int i = 0; i < names.Length; i++) {
                    TreeNodeCollection nodes = node == null? treeView1.Nodes: node.Nodes;
                    node = FindNode(nodes, names[i]);
                    if(node == null)
                        node = nodes.Add(names[i]);
                }
            }
    
            private TreeNode FindNode(TreeNodeCollection nodes, string p) {
                for(int i = 0; i < nodes.Count; i++)
                    if(nodes[i].Text.ToLower(CultureInfo.CurrentCulture) == p.ToLower(CultureInfo.CurrentCulture))
                        return nodes[i];
                return null;
            }