Introduction
There is no file system treeview in .NET 1.1! Therefore I ended up making my own. This is a very basic version of a file system treeview. There are a lot of other methods and or properties that could be added in order to make this a more useful control. However, I have posted this control with the intention that this will save someone some time and aggravation.
Performance is often an issue when dealing with recursion and an extremely large file system. Therefore to overcome this issue I designed this treeview component so it loads on demand. In order to make this happen, I initially only load the root directories and files. Obviously a file can not have any child nodes but a directory on the other hand can have sub-directories and files within it. If a directory has sub-directories and/or files, I add what I describe as a "fake child node". Basically all this means is that I add a child tree node to the "directory node" in order to display the "+" plus sign in front of it. This indicates to the user that they can drill down further to see the sub-directories and files. Here is some example code:
int fileCount = 0;
if( this.TreeView.ShowFiles == true )
fileCount = this._directoryInfo.GetFiles().Length;
if( (fileCount + this._directoryInfo.GetDirectories().Length) > 0 )
new FakeChildNode( this );
The FakeChildNode
class is extremely simple. It derives from the TreeNode
class and only has a single constructor that adds a child node to an existing node.
public class FakeChildNode : TreeNode
{
public FakeChildNode( TreeNode parent ) : base()
{
parent.Nodes.Add( this );
}
}
So now that we have the initial directories loaded and virtualized, we can write the code that controls the on-demand loading of the subnodes. In order to do this, I wrote an event handler for the "BeforeExpand
" event of the treeview.
void FileSystemTreeView_BeforeExpand(object sender,
TreeViewCancelEventArgs e)
{
if( e.Node is FileNode ) return;
DirectoryNode node = (DirectoryNode)e.Node;
if (!node.Loaded)
{
node.Nodes[0].Remove();
node.LoadDirectory();
if( this._showFiles == true )
node.LoadFiles();
}
}
So now that you understand the basic logistics of this control, here is an example of how you can put it to use:
Using the code
C2C.FileSystem.FileSystemTreeView tree =
new C2C.FileSystem.FileSystemTreeView();
Controls.Add( tree );
tree.Dock = DockStyle.Fill;
tree.Load( @"C:\" );