Does anyone know how to bind a directory to a treeview in C# or know of a simple tutorial to follow along with? Thanks
A:
You can use simple recursion .Not sure what exactly you want to display in TreeView but the following approach can work
public static void LoadDir(TreeNode t,DirectoryInfo d) {
TreeNode tn= new TreeNode(d.name);
t.ChildNodes.Add(tn);
foreach(DirectoryInfo dn in d.GetDirectories())
LoadDir(tn,dn); }
You can Invoke it as
TreeNode tn=new TreeNode("Root");
TreeView1.Nodes.Add(tn);
LoadDir(tn,new DirectoryInfo(@"C:\Oracle");
josephj1989
2010-06-08 20:45:37
I am displaying it in a checkable treeview so when the end users selects particular files or folders I will replicate them over to a different location in a Boolean format. Would you suggest another way?
jpavlov
2010-06-08 22:20:27
+1
A:
Something like this:
public void BindDirectoryToTreeView(string directoryPathToBind)
{
TreeNode rootNode = new TreeNode();
treeView1.Nodes.Add(rootNode);
RecurseFolders(directoryPathToBind, rootNode);
}
public void RecurseFolders(string path, TreeNode node)
{
var dir = new DirectoryInfo(path);
node.Text = dir.Name;
try
{
foreach (var subdir in dir.GetDirectories())
{
var childnode = new TreeNode();
node.Nodes.Add(childnode);
RecurseFolders(subdir.FullName, childnode);
}
}
catch (UnauthorizedAccessException ex)
{
// TODO: write some handler to log and/or deal with
// unauthorized exception cases
}
foreach (var fi in dir.GetFiles().OrderBy(c=>c.Name))
{
var fileNode = new TreeNode(fi.Name);
node.Nodes.Add(fileNode);
}
}
You would invoke the code by calling BindDirectoryToTreeView("c:\");
for instance. Note that you should have a treeview named treeView1 on the form that has this code.
code4life
2010-06-08 20:46:09
Where should I call the BindDirectorytoTreeView from to display the directory hierarchy?
jpavlov
2010-06-08 23:18:02
If you want this to bind immediately on form creation, then put it in the constructor of the form. Otherwise you can bind it to a button press, etc. I left the method open so that you can call it from any form event.
code4life
2010-06-09 02:59:16
Thanks. I just tried this and works good, although it doesn't pull every folder off my drive, i will play around with it and see if I can figure it out. Thanks again.
jpavlov
2010-06-09 18:57:27
It seems like this just some hidden files along with the recycle bin. I was hoping to get inetpub folder structure, and other folders with the file included. Do I need another recursive function for this?
jpavlov
2010-06-09 19:07:44