运行效果.jpg
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace TreeViewExample
{
public partial class TreeViewExampleForm : Form
{
public TreeViewExampleForm()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string path = @"E:\学习开发文件夹";
LoadDirectoryAndFile(path, LeftTreeView.Nodes);
}
//将找到的文件夹和文件添加到节点上
private void LoadDirectoryAndFile(string path,TreeNodeCollection tc)
{
//获得当前这一目录下所有文件夹的全路径
string[] dics = Directory.GetDirectories(path);
for (int i = 0; i < dics.Length; i++)
{
//从文件夹的全路径中截取出文件夹的名称
string dicName = Path.GetFileNameWithoutExtension(dics[i]);
//将文件夹的名称添加到节点集合下,返回新添加的节点
TreeNode tn = tc.Add(dicName);
//递归调用自己继续将下级文件夹添加到当前节点下
LoadDirectoryAndFile(dics[i],tn.Nodes);
}
//获得当前文件夹下所有文件的全路径
string[] fileNames = Directory.GetFiles(path);
for (int i = 0; i < fileNames.Length; i++)
{
//从文件的全路径中截取出文件的名称
string fileName = Path.GetFileNameWithoutExtension(fileNames[i]);
TreeNode tn = tc.Add(fileName);
tn.Tag = fileNames[i];
}
}
private void LeftTreeView_MouseDoubleClick(object sender, MouseEventArgs e)
{
//获得选中的节点
string filePath = LeftTreeView.SelectedNode.Tag.ToString();
RighttTextBox.Text = File.ReadAllText(filePath, Encoding.Default);
}
}
}
网友评论