首页 > 代码库 > treeView和递归的简单运用

treeView和递归的简单运用

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace treeview
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            string path = @"F:\demo";
            LoadDirectoryAndFile(treeView1.Nodes,path);
        }
 
        private void LoadDirectoryAndFile(TreeNodeCollection tnc, string path)
        {
            //获取文件夹
           string[] dirs = Directory.GetDirectories(path);
           for (int i = 0; i < dirs.Length; i++)
           {
              TreeNode tn = tnc.Add(Path.GetFileName(dirs[i]));
              LoadDirectoryAndFile(tn.Nodes, dirs[i]);//递归遍历
           }
 
            //获取文件
           string[] files = Directory.GetFiles(path,"*.txt"); //只加载.txt
           for (int i = 0; i < files.Length; i++)
           {
              TreeNode tn1 = tnc.Add(Path.GetFileName(files[i]));
 
               ////Tag:可以存任何东西,在这里存的是文本文件的路径,因为文件夹不需要显示在文本框中
              tn1.Tag = files[i];
           }
        }
 
        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (treeView1.SelectedNode.Tag != null)
            {
                textBox1.Text = File.ReadAllText(treeView1.SelectedNode.Tag.ToString(), Encoding.Default);
            }
        }
    }
}