c# Build a directory tree

2019-08-07 05:28发布

问题:

I am trying to build a directory tree in my application. I am using this Example from Ext.NET. How I can search a given path for directories and sub-directories in order to build this tree?

Here is the code given in the example to build the tree from nodes:

protected void NodeLoad(object sender, NodeLoadEventArgs e)
    {

        if (!string.IsNullOrEmpty(e.NodeID))
        {
            for (int i = 1; i < 6; i++)
            {
                AsyncTreeNode asyncNode = new AsyncTreeNode();
                asyncNode.Text = e.NodeID + i;
                asyncNode.NodeID = e.NodeID + i;
                e.Nodes.Add(asyncNode);
            }

            for (int i = 6; i < 11; i++)
            {
                Ext.Net.TreeNode treeNode = new Ext.Net.TreeNode();
                treeNode.Text = e.NodeID + i;
                treeNode.NodeID = e.NodeID + i;
                treeNode.Leaf = true;
                e.Nodes.Add(treeNode);
            }
        }
    }

回答1:

Something like this:

<script runat="server">
    protected void NodeLoad(object sender, NodeLoadEventArgs e)
    {
        // NodeID stores the local disk path ( full path ) of the selected node to expand
        string path = e.NodeID;

        if (!string.IsNullOrEmpty(e.NodeID))
        {
            foreach(var folder in System.IO.Directory.GetDirectories(path))
            {
                string folderName = new System.IO.DirectoryInfo(folder).Name;
                Node folderNode = new Node();
                folderNode.Text = folderName;
                folderNode.NodeID = folder;
                e.Nodes.Add(folderNode);
            }

            foreach(var fileLeaf in System.IO.Directory.GetFiles(path))
            {
                Node treeNode = new Node();
                treeNode.Text = System.IO.Path.GetFileName(fileLeaf);
                treeNode.NodeID = fileLeaf;
                treeNode.Leaf = true;
                e.Nodes.Add(treeNode);
            }
        }
    }
</script>

For me, I just used C:\ as an example, you'll need to put your root folder in the element:

<Root>
    <ext:Node NodeID="C:\" Text="C:\"/>
</Root>