使用TreeView加载文件夹

Posted jizhiqiliao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用TreeView加载文件夹相关的知识,希望对你有一定的参考价值。

    String Path = "C:\Test";

    private void ListDirectory(TreeView treeView, string path)
    {
        treeView.Nodes.Clear();
        var rootDirectoryInfo = new DirectoryInfo(path);

        treeView.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo));
    }

    private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
    {
        var directoryNode = new TreeNode(directoryInfo.Name);
        foreach (var directory in directoryInfo.GetDirectories())
            directoryNode.Nodes.Add(CreateDirectoryNode(directory));

        foreach (var file in directoryInfo.GetFiles())
            directoryNode.Nodes.Add(new TreeNode(file.Name) { Tag = file });

        return directoryNode;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //string s = treeView1.SelectedNode.ToString();
        //String TreeNodeName = treeView1.SelectedNode.ToString().Replace("TreeNode: ", String.Empty);
        //System.Diagnostics.Process.Start(Path + "\" + TreeNodeName);
        string p = (treeView1.SelectedNode?.Tag as FileInfo)?.FullName;
        if (p != null)
        {
            System.Diagnostics.Process.Start(p);
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        ListDirectory(treeView1, Path);
    }

以上是关于使用TreeView加载文件夹的主要内容,如果未能解决你的问题,请参考以下文章

C#treeView是一个代码,用于将子节点安排为其父节点的最后一个子节点

递归加载省市到TreeView

怎样在treeview中加载数据库 C#

DELPHI 如何打开和 保存 TREEVIEW 的状态

C# treeView 是不是有代码可以将子节点安排为其父节点的最后一个子节点

Kendo UI TreeView动态启用/禁用dragAndDrop事件