自制一个简易资源管理器----TreeView控件
第一步、新建project,进行基本设置;(Set as StartUp Project;View/Toolbox/TreeView)
第二步、开始添加节点
添加命名空间using System.IO;
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 using System.IO; 11 12 namespace _ResouceManager_ 13 { 14 public partial class Form1 : Form 15 { 16 public Form1() 17 { 18 InitializeComponent(); 19 } 20 21 private void Form1_Load(object sender, EventArgs e) 22 { 23 //这里是资源管理器的根路径 24 string strRoot = @"H:\自制资源管理器";//路径 25 CreateParent(strRoot); 26 } 27 28 private void CreateParent(string strRoot) 29 { 30 //创建根节点parent 31 TreeNode parent = new TreeNode(); 32 DirectoryInfo di=new DirectoryInfo(strRoot); 33 parent.Text= di.Name ; 34 parent.Tag = di.FullName; 35 36 //添加父节点 37 tvResouceManager.Nodes.Add(parent); 38 39 //创建子节点 40 CreateChild(strRoot,parent); 41 //展开所有节点 42 parent.ExpandAll(); 43 44 } 45 46 private void CreateChild(string path,TreeNode parent ) 47 { 48 DirectoryInfo di = new DirectoryInfo(path); 49 //所有的子文件夹 50 DirectoryInfo[] dirs = di.GetDirectories(); 51 //遍历子文件夹 52 foreach(DirectoryInfo dir in dirs) 53 { 54 //创建子节点 55 TreeNode child = new TreeNode(); 56 child.Text = dir.Name; 57 //child.Tag = dir.FullName; 58 59 //添加子节点 60 parent.Nodes.Add(child); 61 62 //递归实现多级文件夹的遍历、创建子节点、添加子节点 63 CreateChild(dir.FullName,child); 64 65 //添加文件节点 66 CreateFile(dir.FullName,child); 67 } 68 } 69 70 private void CreateFile(string p, TreeNode child) 71 { 72 DirectoryInfo di = new DirectoryInfo(p); 73 //路径下的所有文件 74 FileInfo[] files = di.GetFiles(); 75 //添加路径下的所有文件 76 foreach(FileInfo file in files) 77 { 78 //创建节点 79 TreeNode tn = new TreeNode(); 80 tn.Text = file.Name; 81 // tn.Tag = file.FullName; 82 83 //添加节点 84 child.Nodes.Add(tn); 85 } 86 } 87 88 } 89 }