1、代码
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 TestApp
{public partial class MainForm : Form{public MainForm(){InitializeComponent();}private void BtnConfig_Click(object sender, EventArgs e){treeView1.Nodes.Clear();string root = TbRoot.Text;if(Directory.Exists(root) ){TreeNode treeNode = new TreeNode(root);treeView1.Nodes.Add(treeNode);FindDirectory(root, treeNode);}else{MessageBox.Show("输入目录不存在!");TbRoot.Clear();treeView1.Nodes.Clear();}}private void FindDirectory(string root, TreeNode parentNode){try{string[] arr = Directory.GetDirectories(root);if (arr.Length > 0){foreach (string item in arr){string str = Path.GetFileNameWithoutExtension(item);TreeNode node = new TreeNode(str);parentNode.Nodes.Add(node);FindDirectory(item, node);}}}catch (Exception ex){MessageBox.Show(ex.Message);}}TreeNode currentNode = null;private void treeView2_AfterSelect(object sender, TreeViewEventArgs e){currentNode = e.Node;}int i = 0;private void BtnAddNode_Click(object sender, EventArgs e){if (treeView2.Nodes.Count > 0){TreeNode node = new TreeNode($"节点{i++}");currentNode.Parent.Nodes.Add(node);}else{TreeNode node = new TreeNode("首节点");treeView2.Nodes.Add(node);}}private void BtnAddSonNode_Click(object sender, EventArgs e){if (treeView2.Nodes.Count > 0){TreeNode node = new TreeNode($"节点{i++}");currentNode.Nodes.Add(node);}}private void BtnDeleteNode_Click(object sender, EventArgs e){treeView2.Nodes.Remove(currentNode);}}
}
2、运行结果