using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace ExplorerDemo2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] drives = Directory.GetLogicalDrives();
foreach (string drive in drives)
{
TreeNode tn = new TreeNode(); //例如c:/
tn.Text =drive;
tn.Name = drive;
this.treeView1.Nodes.Add(tn);
try
{
string[] folders = Directory.GetDirectories(drive);
foreach (string folder in folders)
{
TreeNode tm=new TreeNode(); //例如 c:/windows
tm.Name = folder; //path
//MessageBox.Show(tm.Name);
tm.Text = folder.Substring(folder.LastIndexOf("//")+1);
tn.Nodes.Add(tm); //添加驱动器下的所有文件夹
//tn.ExpandAll(); //展开所有
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void treeView1_AfterExpand(object sender, TreeViewEventArgs e)
{
TreeNode tn = e.Node; //例如 c:/
tn.Name = e.Node.Name;
//MessageBox.Show(e.Node.Text);
treeView1.SelectedNode = e.Node;
tn.Nodes.Clear(); //避免重复添加
try
{
string[] folders = Directory.GetDirectories(tn.Name);
foreach (string folder in folders)
{
TreeNode tm = new TreeNode(); //例如c:/windows
tm.Name = folder;
tm.Text = folder.Substring(folder.LastIndexOf("//")+1);
//MessageBox.Show(tm.Name+"|"+tm.Text);
tn.Nodes.Add(tm); // c:/windows
string[] foldersons = Directory.GetDirectories(tm.Name); //例如:windows/system32
foreach (string folderson in foldersons)
{
TreeNode sunNode = new TreeNode();
sunNode.Name = folderson;
sunNode.Text = folderson.Substring(folderson.LastIndexOf("//")+1);
tm.Nodes.Add(sunNode);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}//利用node的name属性来保存路径,用node的text属性来保存路径切割后的值(即文件夹的名字)
}
}
}