wayne on April 22, 2008
As an update to my post on recursively populating a treeview with folders, I added code that will also provide files into TreeView control.
Here is the full populateTree routine with files being added:
/// <summary>
/// Popultates child nodes under the provided Treenode object. Nodes are
/// populated with folder names found under the startingPath provided.
/// </summary>
/// <param name="startingPath">The root of the tree</param>
/// <param name="tn">The root node object</param>
private void populateTree(string startingPath, ref TreeNode tn)
{
TreeNode tnAdd = null;
// Obtain all subfolders first
DirectoryInfo di = new DirectoryInfo(startingPath);
DirectoryInfo[] dirs = di.GetDirectories("*", SearchOption.TopDirectoryOnly);
//Iterate through each folder, drilling down to the lowest level in each
foreach (DirectoryInfo dis in dirs)
{
// Create a new node to add
tnAdd = new TreeNode(dis.Name, dis.Name);
// Check for children folders of the new node
populateTree(dis.FullName, ref tnAdd);
// Obtain files found in the current folder
FileInfo[] fi = dis.GetFiles("*", SearchOption.TopDirectoryOnly);
foreach (FileInfo fiItem in fi)
tnAdd.ChildNodes.Add(new TreeNode(fiItem.Name));
if (tnAdd != null)
// Add the child to the node collection
tn.ChildNodes.Add(tnAdd);
}
}
Performance of this routine is directly impacted by the size of the file system. As such one would want to consider the file system before implementing, I guess. I would look to reorganize a file system with 50k files before even thinking of using any tree...
There is another school of thought that says large trees should be loaded with nodes as they are needed, or perhaps even asynchronously. For a web page however, unless you work in some fancy AJAX or don't mind all the postbacks, it's probably best to load the entire tree at page_load. It will depend on the need in the end.