创建根节点
/// 树形图 创建根节点
/// </summary>
/// <param name="textBox1">输入textBox值</param>
/// <param name="treeView1">输入treeView</param>
/// <param name="savePath">路径</param>
public static void createRoot(TextBox textBox1, TreeView treeView1, string savePath) {
if (string.IsNullOrEmpty(textBox1.Text.Trim()))//判断为空
{
MessageBox.Show("不能为空", "树形图提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
//创建初始路径
if (!Directory.Exists(savePath))//false
{
//创建文件夹
System.IO.Directory.CreateDirectory(savePath);
}
//判断该根节点存在不
if (!Directory.Exists(Application.StartupPath + "\\" + savePath + "\\" + textBox1.Text.Trim()))
{
//创建文件 文件路径
System.IO.Directory.CreateDirectory(Application.StartupPath + "\\" + savePath + "\\" + textBox1.Text.Trim());
//添加 树形图
treeView1.Nodes.Add(textBox1.Text.Trim());
}
else
{
MessageBox.Show("该根节点名称已存在", "树形图");
}
//展开树形图
treeView1.ExpandAll();
textBox1.Text = "";
}
添加子节点
/// <summary>
/// 树形图 创建子节点
/// </summary>
/// <param name="textBox1">输入textBox值</param>
/// <param name="treeView1">输入treeView</param>
/// <param name="savePath">路径</param>
public static void createChildNode(TextBox textBox1, TreeView treeView1,string savePath) {
TreeNode lishi = null;
string str = "";
if (treeView1.SelectedNode != null)
{
lishi = treeView1.SelectedNode;
str = treeView1.SelectedNode.Text;
while (treeView1.SelectedNode.Parent != null)
{
string val = treeView1.SelectedNode.Parent.Text;
str = val + "\\" + str;
// 选中父节点
treeView1.SelectedNode = treeView1.SelectedNode.Parent;
}
// 之后完成之后重新选中会到选中位置
treeView1.SelectedNode = lishi;
// string path = Application.StartupPath + "\\"+ savePath + "\\" + str;
if (Directory.Exists(Application.StartupPath + "\\" + savePath + "\\" + str + "\\" + textBox1.Text.Trim()))
{
MessageBox.Show("该文件夹已存在", "树形图");
return;
}
treeView1.SelectedNode.Nodes.Add(textBox1.Text.Trim());
System.IO.Directory.CreateDirectory(Application.StartupPath + "\\" + savePath + "\\" + str + "\\" + textBox1.Text.Trim());
}
textBox1.Text = "";
}
删除节点
/// <summary>
/// 树形图 删除节点
/// </summary>
/// <param name="treeView1">输入treeView</param>
/// <param name="savePath">路径</param>
public static void deleteNode( TreeView treeView1, string savePath) {
TreeNode lishi = null;
string str = "";
if (treeView1.SelectedNode != null)
{
lishi = treeView1.SelectedNode;
str = treeView1.SelectedNode.Text;
//
while (treeView1.SelectedNode.Parent != null)
{
string val = treeView1.SelectedNode.Parent.Text;
str = val + "\\" + str;
// 选中父节点
treeView1.SelectedNode = treeView1.SelectedNode.Parent;
}
// 之后完成之后重新选中会到选中位置
treeView1.SelectedNode = lishi;
}
DirectoryInfo di = new DirectoryInfo(Application.StartupPath + "\\" + savePath + "\\" + str);
FileAttributes attr = File.GetAttributes(Application.StartupPath + "\\" + savePath + "\\" + str);
if (di.Exists)
{
Directory.Delete(Application.StartupPath + "\\" + savePath + "\\" + str, true);
}
if (treeView1.SelectedNode == null)
{
MessageBox.Show("请选择要删除的节点!");
return;
}
treeView1.SelectedNode.Remove();
}