C# How to use treeView to list the directories and subdirectories without showing the root directory?

后端 未结 1 881
傲寒
傲寒 2021-01-25 23:37

From

main folder
|_a
| |_b
| |_c
|_d
|_e

to

a
 |_b
 |_c
d
e

I want a treeview without the main folder. I foun

1条回答
  •  被撕碎了的回忆
    2021-01-26 00:13

    Try this, it looks real fast here. You can control whether all nodes are expanded or not.. You need to included the LINQ namspace (using System.Linq;)

    // somewhere:
    string yourRoot = "D:\\";
    treeView1.Nodes.AddRange(getFolderNodes(yourRoot, true).ToArray());
    
    private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
    {
        TreeNode tn = e.Node.Nodes[0];
        if (tn.Text == "...")
        {
            e.Node.Nodes.AddRange(getFolderNodes(((DirectoryInfo)e.Node.Tag)
                  .FullName, true).ToArray());
            if (tn.Text == "...") tn.Parent.Nodes.Remove(tn);
        }
    }
    
    List getFolderNodes(string dir, bool expanded)
    {
        var dirs = Directory.GetDirectories(dir).ToArray();
        var nodes = new List();
        foreach (string d in dirs)
        {
            DirectoryInfo di = new DirectoryInfo(d);
            TreeNode tn = new TreeNode(di.Name);
            tn.Tag = di;
            int subCount = 0;
            try { subCount = Directory.GetDirectories(d).Count();  } 
            catch { /* ignore accessdenied */  }
            if (subCount > 0) tn.Nodes.Add("...");
            if (expanded) tn.Expand();   //  **
            nodes.Add(tn);
        }
        return nodes;
    }
    

    If you are sure you always want to see all levels expaded from the start you can use this function and delete the BeforeExpand code:

    List getAllFolderNodes(string dir)
    {
        var dirs = Directory.GetDirectories(dir).ToArray();
        var nodes = new List();
        foreach (string d in dirs)
        {
            DirectoryInfo di = new DirectoryInfo(d);
            TreeNode tn = new TreeNode(di.Name);
            tn.Tag = di;
            int subCount = 0;
            try { subCount = Directory.GetDirectories(d).Count(); } 
            catch { /* ignore accessdenied */  }
            if (subCount > 0)
            {
                var subNodes = getAllFolderNodes(di.FullName);
                tn.Nodes.AddRange(subNodes.ToArray());
            }
            nodes.Add(tn);
        }
        return nodes;
    }
    

    You call it as before:

    string yourRoot = "D:\\";
    Cursor.Current = Cursors.WaitCursor;
    treeView1.Nodes.AddRange(getAllFolderNodes(yourRoot).ToArray());
    Cursor.Current = Cursors.Default;
    

    0 讨论(0)
提交回复
热议问题