Introduction
I've been checking around and most of the .NET solutions for file browsing I've found are built around Win API invocations. Among other considerations, which means that those apps would be accessing unmanaged resources and because of that, they will be requiring very high CAS permissions to run and may implicate security risks. Please also have in mind that despite the fact that you won't be invoking any API, there are some other security constraints that you may be facing, like having the necessary CAS permissions to run the app or the system permissions to allow the user running the app to access the file system (Role Based Security).
Background
There is no special background required to understand how the code works.
Using the Code
There are just a few points to remark.
First, always check whether the drives you are about to list are ready or not before trying to access them (to read content or drive's properties). This may seem trivial but if you don't, you'll probably end up with exceptions and big delays when working with optical/magnetic/network mapped drives.
private void Form1_Load(object sender, EventArgs e) {
foreach(DriveInfo di in DriveInfo.GetDrives()) {
TreeNode tn = new TreeNode();
string nodeText = string.Empty;
if (di.IsReady)
Second, you will find this method...
private TreeNode AddChildNodes(TreeNode node, bool final) {
if (final) {
return node;
}
The final
parameter is intended to stop navigating the tree when the passed node is a final node (a leaf of the tree). If you try to read child nodes of a leaf, you will get an exception. This workaround is more related with the way in which I implemented this solution than with the nature of the issue itself. There are many other ways to workaround this.
Finally, you may notice that I'm filling the corresponding node of all folders with its immediate children as soon as they appear on the left pane (even when these children folders are not being displayed).
private void tvFolders_AfterExpand(object sender, TreeViewEventArgs e) {
foreach (TreeNode node in e.Node.Nodes) {
AddChildNodes(node, false);
}
}
That is intended to make the + on the left of the displayed folders. Once more, there are many other ways of working this out. I just considered that this was the best suited to this solution.
Final Comments
I hope this helps you...
History
- 27th October, 2007: Initial post