此代码可以正常工作:
private void Form1_Load(object sender, EventArgs e)
{
PopulateTree(@"C:\treeview", treeView1.Nodes.Add("I want to remove this node"));
}
public void PopulateTree(string dir, TreeNode node)
{
DirectoryInfo directory = new DirectoryInfo(dir);
foreach (DirectoryInfo d in directory.GetDirectories())
{
TreeNode t = new TreeNode(d.Name);
PopulateTree(d.FullName, t);
node.Nodes.Add(t);
}
foreach (FileInfo f in directory.GetFiles())
{
TreeNode t = new TreeNode(f.Name);
node.Nodes.Add(t);
}
}
但是,我不想在子目录列表的顶部显示main(= root)目录(=文件夹),我只想显示图中所示的子目录。
答案 0 :(得分:1)
PopulateTree(@"C:\treeview", treeView1.Nodes);
public void PopulateTree(string dir, TreeNodeCollection nodes)
{
DirectoryInfo directory = new DirectoryInfo(dir);
foreach (DirectoryInfo d in directory.GetDirectories())
{
TreeNode t = new TreeNode(d.Name);
nodes.Add(t);
PopulateTree(d.FullName, t.Nodes);
}
foreach (FileInfo f in directory.GetFiles())
{
TreeNode t = new TreeNode(f.Name);
nodes.Add(t);
}
}
答案 1 :(得分:1)
试试这个:
public void PopulateTree(string dir, TreeNode node)
{
DirectoryInfo directory = new DirectoryInfo(dir);
foreach (DirectoryInfo d in directory.GetDirectories())
{
TreeNode t = new TreeNode(d.Name);
if (node != null) node.Nodes.Add(t);
else treeView1.Nodes.Add(t);
PopulateTree(d.FullName, t);
}
foreach (FileInfo f in directory.GetFiles())
{
TreeNode t = new TreeNode(f.Name);
if (node != null) node.Nodes.Add(t);
else treeView1.Nodes.Add(t);
}
}
private void Form1_Load(object sender, EventArgs e)
{
PopulateTree(@"C:\treeview", null);
}