24
我是新与节点这里.. :)我想出了这个算法,但它只能显示父节点列表..这样的..填充的TreeView与文件系统的目录结构
a
a.txt
b
c
c
m
n
b
o
p
etc...
我想下一个节点将被放置在前面的节点..里面的节点之一,所以它会想出这样的..
a
a.txt
b
o
p
c
m
n
etc...
我心中有一个想法,但我可以把它落实代码。 。:)请任何帮助..
private void ListDirectory(TreeView treeView, String path)
{
Stack<string> stack = new Stack<string>();
TreeNode DirFilesCollection = new TreeNode();
stack.Push(path);
while (stack.Count > 0)
{
string dir = stack.Pop();
try
{
List<String> parentDir = new List<string>();
parentDir.AddRange(Directory.GetFiles(dir, "*.*"));
parentDir.AddRange(Directory.GetDirectories(dir));
DirectoryInfo d = new DirectoryInfo(dir);
TreeNode TParent = new TreeNode(d.Name);
foreach (String s in parentDir)
{
FileInfo f = new FileInfo(s);
TreeNode subItems = new TreeNode(f.Name);
TParent.Nodes.Add(subItems);
}
DirFilesCollection.Nodes.Add(TParent);
foreach (string dn in Directory.GetDirectories(dir))
{
stack.Push(dn);
}
}
catch
{}
}
Action clearTreeView =() => treeView.Nodes.Clear();
this.Invoke(clearTreeView);
Action showTreeView =() => treeView.Nodes.Add(DirFilesCollection);
this.Invoke(showTreeView);
}
@vrynxzent - 如果你有兴趣,更新的答案也是非递归方法。 – 2011-06-04 22:12:51
ahh ..我看到..我更喜欢使用非递归,因为线程和尝试catch ..我也可以在递归方法中做到这一点,但我需要看到在获取文件和目录时更新数据的窗体.. – 2011-06-04 23:32:24
我使用递归和迭代函数,这是我的代码,但compler返回一个错误:**访问路径'E:\ System Volume Information'被拒绝。这是我的代码:** ListDirectory(treeView1,@“E:\”); ** – 2012-09-12 19:12:26