treeview绑定硬盘数据文件

using System.IO;
using System.Management;

public class BindFiles
{
private TreeView treeView1;

public BindFiles(TreeView tree)
{
treeView1 = tree;
}

//绑定treeView
public void GetTreeNode()
{
this.treeView1.Nodes.Clear();
SelectQuery selectQuery = new SelectQuery("select * from win32_logicaldisk");
  ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery);
int i = 0;
  foreach (ManagementObject disk in searcher.Get())
{
if(disk["DriveType"].ToString() == "3")
{
TreeNode node = new TreeNode();
node.Text = disk["Name"].ToString();
node.Tag = disk["Name"].ToString()+"//";
node.ImageIndex = 0;
this.treeView1.Nodes.Add(node);

//开始不想加载子文件,完则将此句代码注释
InsertTree(treeView1.Nodes[i].Nodes, disk["Name"].ToString());

i ++;
}
}
}

/// <summary>
/// 填充treeView节点
/// </summary>
/// <param name="nodes">要填充节点的父节点的子节点集合</param>
/// <param name="dir">父节点所代表的路径</param>
public void InsertTree(TreeNodeCollection nodes, string dir)
{
string[] cats = new string[0];
try { cats = Directory.GetDirectories(dir); }
catch { }
if(cats.Length>0)
{
foreach( string cat in cats)
{
TreeNode node = new TreeNode();
node.Text = cat.Substring(cat.LastIndexOf("//")+1);
node.Tag = cat+"//";
node.ImageIndex = 1;
node.SelectedImageIndex = 2;
nodes.Add(node);
nodes[nodes.Count-1].EnsureVisible();
//不想一次性加载完所有子文件,则将此句代码注释
InsertTree(node.Nodes, cat);
}
}
}
}

你可能感兴趣的:(treeview)