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);
}
}
}
}
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
BdTreeView(AppDomain.CurrentDomain.BaseDirectory,TreeView1.Nodes);
}
}
public void BdTreeView(string dir, TreeNodeCollection tc)
{
DirectoryInfo di = new DirectoryInfo(dir);
DirectoryInfo[] sunDir = di.GetDirectories();
FileInfo[] ffi = di.GetFiles();
foreach (DirectoryInfo i in sunDir)
{
TreeNode tn = new TreeNode();
tn.Text = Path.GetFileName(i.FullName);
tc.Add(tn);
BdTreeView(i.FullName, tn.ChildNodes);
}
foreach (FileInfo j in ffi)
{
TreeNode fileNode = new TreeNode();
fileNode.Text = System.IO.Path.GetFileName(j.FullName);
tc.Add(fileNode);
}
}
}
}
http://blog.csdn.net/lee576/archive/2008/11/04/3219523.aspx