To create tree view of directories

Feb 9 2011 1:18 AM
I am creating an application that displays the drives, directories inside them and the sub-directories and the files all in a tree like format.

I am using a TreeView control in C#.net

The problem is that sometimes it doesn't show some of the subdirectories or it skips some of the files and most of the time, it misses the name of the directories.

Here's what i have written:


  private void button1_Click(object sender, EventArgs e)
        { 
treeView1.Nodes.Add("My Computers");
            TreeNode child = new TreeNode();
            TreeNode chNode = new TreeNode();
            DirectoryInfo direObj = new DirectoryInfo("F:\\Tushar\\E-Books");
            treeView1.Nodes.Add(direObj.Name);
            foreach (DirectoryInfo d in direObj.GetDirectories())
            {
                child .Nodes .Add (d.FullName );
                chNode.Nodes .Add (GetDir(d));
            }
            child.Nodes.Add(chNode);
            treeView1.Nodes.Add(child);
	}
/* this is the exact logic of creating a treeNode and assigning it 
with the directory name or the sub-Directory name or the file name
*/
 /*
The recursive function that searches the sub-directories and the 
files is :
*/

TreeNode GetDir(DirectoryInfo di)
        {
            TreeNode SubNode = new TreeNode();
            foreach (DirectoryInfo d in di.GetDirectories())
            {
                SubNode.Nodes.Add(d.FullName);
                TreeNode ChildNode = new TreeNode();
                foreach (FileInfo file in d.GetFiles("*.*"))
                {                    
                    ChildNode.Nodes.Add(file.FullName );
                }
                SubNode.Nodes.Add(ChildNode);
                GetDir(d);
            }
            return SubNode;
        }

Answers (3)