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);
}
}
}
}
|