TreeView 递归列出电脑所有盘符
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
private void FormTreeView_Load(object sender, EventArgs e)
{
FilltvwDirectory();
}
private void FilltvwDirectory()
{
//获取当前设备盘符,并添加到数组dires[i]里面
string[] dires = Environment.GetLogicalDrives();
int diresLength = dires.Length;
for (int i = 0; i < diresLength; i++)
{
TreeNode cRoot = new TreeNode(dires[i]);
tvwDirectory.Nodes.Add(cRoot);
AddDirectories(cRoot);
}
}
private void AddDirectories(TreeNode node)
{
try
{
//获取当前节点路径
DirectoryInfo dir = new DirectoryInfo(GetPathFromNode(node));
DirectoryInfo[] e = dir.GetDirectories();
int eLength = e.Length;
for (int i = 0; i < eLength; i++)
{
string name = e[i].Name;
//判断是否是上级目录
if (!name.Equals(".") && !name.Equals(".."))
{
node.Nodes.Add(name);
}
}
}
catch (Exception e)
{
// MessageBox.Show(e.Message);
}
}
private string GetPathFromNode(TreeNode node)
{
if (node.Parent == null)
{
return node.Text;
}
//递归调用产生节点对应文件夹的路径
//Path.Combine组合产生路径,如Path.Combine("A","B")则生成"A\\B"
return Path.Combine(GetPathFromNode(node.Parent), node.Text);
}
private void AddSubDirectories(TreeNode node)
{
int nodesCount = node.Nodes.Count;
for (int i = 0; i < nodesCount; i++)
{
AddDirectories(node.Nodes[i]);
}
}
//在将要展开节点时发生
private void tvwDirectory_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
TreeNode nodeExpanding = (TreeNode)e.Node;
AddSubDirectories(nodeExpanding);
}
{
FilltvwDirectory();
}
private void FilltvwDirectory()
{
//获取当前设备盘符,并添加到数组dires[i]里面
string[] dires = Environment.GetLogicalDrives();
int diresLength = dires.Length;
for (int i = 0; i < diresLength; i++)
{
TreeNode cRoot = new TreeNode(dires[i]);
tvwDirectory.Nodes.Add(cRoot);
AddDirectories(cRoot);
}
}
private void AddDirectories(TreeNode node)
{
try
{
//获取当前节点路径
DirectoryInfo dir = new DirectoryInfo(GetPathFromNode(node));
DirectoryInfo[] e = dir.GetDirectories();
int eLength = e.Length;
for (int i = 0; i < eLength; i++)
{
string name = e[i].Name;
//判断是否是上级目录
if (!name.Equals(".") && !name.Equals(".."))
{
node.Nodes.Add(name);
}
}
}
catch (Exception e)
{
// MessageBox.Show(e.Message);
}
}
private string GetPathFromNode(TreeNode node)
{
if (node.Parent == null)
{
return node.Text;
}
//递归调用产生节点对应文件夹的路径
//Path.Combine组合产生路径,如Path.Combine("A","B")则生成"A\\B"
return Path.Combine(GetPathFromNode(node.Parent), node.Text);
}
private void AddSubDirectories(TreeNode node)
{
int nodesCount = node.Nodes.Count;
for (int i = 0; i < nodesCount; i++)
{
AddDirectories(node.Nodes[i]);
}
}
//在将要展开节点时发生
private void tvwDirectory_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
TreeNode nodeExpanding = (TreeNode)e.Node;
AddSubDirectories(nodeExpanding);
}