Click here to Skip to main content
15,878,959 members
Articles / Programming Languages / C#

Scan Hard Drive into TreeView

Rate me:
Please Sign up or sign in to vote.
2.82/5 (18 votes)
13 Apr 2008CPOL3 min read 46.5K   1.5K   24   4
Scan a hard drive file structure and map it out in a TreeView control with C#.

scanFiles.gif

Introduction

In this article, I’m going to tackle a double whammy: scanning through directories, and adding their paths to a TreeView control. Both methods will require the extremely powerful and sometimes elusive technique of recursion. I’ll leave the practicality of the functions to your imagination.

Directories and Files

Accessing a directory and getting the list of directories and files within it is not the difficult part, for luckily the .NET Framework provides us with a beautiful Directory class that takes care of that for us. The interesting part is accessing subdirectories, and their subdirectories, and their subdirectories. So, how do we know when to stop? Well, we don’t. That is when recursion kicks in.

Recursion is when a function calls itself. For example:

C#
public string recursiveMethod(string inputString)
{
    return recursiveMethod("1") + "2";
}

Now, really looking at this function, it is useless, it will never stop calling itself. But, that is simply because it is poorly structured. The point, however, is that using recursion, we can go through a directory’s subdirectories and their subdirectories without ever needing to know the exact number of them.

So basically, we have code that looks like this:

C#
private void scanFolder(string folderLocation)
{
   //Subdirectories
   foreach (string dir in Directory.GetDirectories(rootDirectory))
   {
       Application.DoEvents(); //Prevent application from hanging
       //don't count recycle bin as folder
       if (dir.ToLower().IndexOf("$recycle.bin") == -1) 
           scanFiles(dir); //recursive call
   }

   //Files
   foreach (string file in Directory.GetFiles(rootDirectory))
   {
       Application.DoEvents();
       //null because we might not have the first node yet
       addNode(file, null); 
   }
}

Notice that the function first scans all levels of directories, and then scans the local files. This is so the final structure will look like Windows Explorer:

Directory
Directory
File
File

Also note how the only thing being added anywhere (a tree node in this case) is the file locations. This behavior works on our example because we will be automatically creating the needed folders from the file path.

Creating the Nodes

The main objective in adding the node is creating a function that you can supply a string such as “C:\Folder1\Folder2\file1.txt” and the proper nodes and child nodes will be created without duplicates.

Once again, we will employ our friend, Recursion. First, we must go back to theory. What keeps a recursive function from calling itself in an endless loop? The answer is a base case. The base case tells the function when it is okay to not call itself again.

In the code above, the base case is built in the subdirectory for-loop. When there are no subdirectories, the function does not call itself.

Back to the TreeView, our base case will be keeping track of the backslashes in the path. Once we have no more backslashes, we have reached the file part of the path.

This time, to keep it simple, some pseudo-code:

Private void addNode(string path, TreeNode parent)
{ 
    If the parent is null (aka first time the function is being called)
        Look for the character ‘:’ (we are probably looking for something like C:\)
        Either reference or create the C:\ node

    //Recursive calls will start here
    If indexOf("\") != -1 (meaning folders still to add)
        The folder name is end at the first backslash (\);
        Either reference or create the folder-name node (in the parent node)
        Call addNode with the rest of the Path, and the referenced node as a parent
    Else (this is the end of the path, aka the file)
        Add the filename to the parent node
}

Now, it should make sense why we didn’t need the explicit folder locations in the list of files. Simply by adding all the files to the same tree node, the folder will be created and common files will be grouped together.

Conclusion

To start of the chain reaction of these functions, all one needs is the starting path, which in this case will be the hard drive to scan (“C:\”, “D:\”, etc). What if you don’t know what drives there are?

Luckily for us, I wrote out a simple routine to get all the available hard drives and let the user pick the one to map out.

Once you run it, you will also notice mapping out the folder structure is extremely slow compared to Windows Explorer. This is simply because Windows Explorer is by no means scanning your entire hard drive every time you open it. It keeps tables already written, and updates and access them as you interact with Windows. That is beyond the scope of this article.

The point of this article was to work a bit with recursion to write out two commonly searched for functions.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Visit Visual C# Kicks for more free C#.NET articles, resources, and downloads at
http://www.vcskicks.com

Comments and Discussions

 
GeneralConvert it Pin
KosayHatem26-Jan-11 23:15
KosayHatem26-Jan-11 23:15 
GeneralFolder icons Pin
hcahcahca8-Jun-09 12:01
hcahcahca8-Jun-09 12:01 
Questionperfect u r my savior Pin
Hasbi Allah22-Apr-09 9:37
Hasbi Allah22-Apr-09 9:37 
AnswerRe: perfect u r my savior Pin
VCSKicks22-Apr-09 10:31
VCSKicks22-Apr-09 10:31 
Glad you liked it!

Honestly I'm not sure how you would implement a progressbar since you need the total number of files in the drive somehow.

The best I can think of is a progressbar for each document by setting it to the length of the array from the function GetFiles

Visual C# Kicks - Free C#.NET articles, resources, and downloads at
http://www.vcskicks.com

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.