Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File System TreeView

Im working with file systems and I have a List<> of file objects that have the file path as a property. Basically I need to create a treeview in .NET but im struggling to think of the best way to go about doing this as I need to create a tree structure from a list like:

C:/WINDOWS/Temp/ErrorLog.txt
C:/Program Files/FileZilla/GPL.html
C:/Documents and Settings/Administrator/ntuser.dat.LOG

etc....

The list is not structured at all and I cant make any changes to the current object structure.

I'm working in C#.

Many thanks for all who contribute

like image 415
user31849 Avatar asked Mar 23 '09 15:03

user31849


1 Answers

If you wanted to stick with the strings something like this would work...

TreeNode root = new TreeNode();
TreeNode node = root;
treeView1.Nodes.Add(root);

 foreach (string filePath in myList) // myList is your list of paths
 {
    node = root;
    foreach (string pathBits in filePath.Split('/'))
    {
      node = AddNode(node, pathBits);
    }
 }


private TreeNode AddNode(TreeNode node, string key)
{
    if (node.Nodes.ContainsKey(key))
    {
        return node.Nodes[key];
    }
    else
    {
        return node.Nodes.Add(key, key);
    }
}
like image 158
PaulB Avatar answered Oct 12 '22 03:10

PaulB