WinForm-1-TreeView文件管理

使用TreeView文件管理,代码如下,最后截图为运行结果

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string _path = @"E:\桌面备份";
            LoadDate(_path, trvFile.Nodes);
        }


        /// <summary>
        /// 获取并加载文件信息
        /// </summary>
        /// <param name="_path"></param>
        /// <param name="treeNodeCollection"></param>
        private void LoadDate(string _path, TreeNodeCollection treeNodeCollection)
        {
            //获取路径
            string[] dics = Directory.GetDirectories(_path);
            foreach (var item in dics)
            {
                //只显示文件名不显示路径
                TreeNode node = treeNodeCollection.Add(Path.GetFileName(item));
                //如果是路径直接递归查询子文件夹的路径
                LoadDate(item, node.Nodes);
            }


            //获取文件,只获取txt类型的文件
            string[] files = Directory.GetFiles(_path, "*.txt");
            foreach (var item in files)
            {
                //只显示文件名不显示路径
                TreeNode node = treeNodeCollection.Add(Path.GetFileName(item));
                //用tag保存路径
                node.Tag = item;
            }
        }


        /// <summary>
        /// 双击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void trvFile_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            TreeNode node = trvFile.SelectedNode;
            //如果没有保存路径直接忽略
            if (!string.IsNullOrEmpty(node.Tag.ToString()))
            {
                txtFile.Text = File.ReadAllText(node.Tag.ToString(), Encoding.Default);
            }
        }
    }











猜你喜欢

转载自blog.csdn.net/m0_37532448/article/details/80926865
今日推荐