用TreeView以递归显示选择磁盘上文件夹中全部文件夹和文件

using System;
using System.IO;
using System.Windows.Forms;

namespace FileManager
{
    public partial class FormFM : Form
    {
        public FormFM()
        {
            InitializeComponent();
        }

        private void BtnSelect_Click(object sender, EventArgs e)
        {
            //清除目录节点
            tvFolder.Nodes.Clear();
            //打开文件夹对话框
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            DialogResult result = fbd.ShowDialog();
            if (result == DialogResult.OK)
            {
                this.txtFilePath.Text = fbd.SelectedPath;
                //根节点
                TreeNode rootNode = new TreeNode();
                //用tag存放全路径,以备递归方法中用
                rootNode.Tag = txtFilePath.Text;
                //根节点文件夹名
                rootNode.Text = txtFilePath.Text.Substring(txtFilePath.Text.LastIndexOf("\") + 1);
                //根节点文件夹名添加到treeview
                tvFolder.Nodes.Add(rootNode);
                //调用递归方法查找文件夹
                LoadFolder(rootNode);
                //根目录
                DirectoryInfo rootDirectoryInfo = new DirectoryInfo(txtFilePath.Text);
                //根目录下的所有文件
                FileInfo[] myFile = rootDirectoryInfo.GetFiles();
                foreach (FileInfo item in myFile)
                {
                    //文件加入到根目录节点下
                    rootNode.Nodes.Add(item.Name);
                }
            }
        }

        /// <summary>
        /// 递归查找文件夹及文件夹中的文件
        /// </summary>
        /// <param name="childNode"></param>
        public void LoadFolder(TreeNode childNode)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(childNode.Tag.ToString());
            try
            {
                DirectoryInfo[] list = directoryInfo.GetDirectories();
                foreach (DirectoryInfo di in list)
                {
                    TreeNode tn = new TreeNode();
                    tn.Text = di.Name;//目录名
                    tn.Tag = di.FullName;
                    FileInfo[] arrfi = di.GetFiles();//目录中的文件名
                    foreach (FileInfo fi in arrfi)
                    {
                        TreeNode tn1 = new TreeNode();
                        tn1.Text = fi.Name;
                        tn1.Tag = fi.FullName;
                        tn.Nodes.Add(tn1);
                        LoadFolder(tn1);
                    }
                    childNode.Nodes.Add(tn);
                    LoadFolder(tn);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                //throw new Exception(ex.Message);
            }
        }
    }
}
原文地址:https://www.cnblogs.com/fooke/p/11519184.html