views:

54

answers:

2

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
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
+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
Where should I call the BindDirectorytoTreeView from to display the directory hierarchy?
jpavlov
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
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
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