C# Programming > Data

C# Scanning a HardDrive to TreeView



Here is how to use C# to scan through files recursively in a computer and add them to a TreeView control. The result will be a C# treeview with folders and files. There are two main functions to accomplish the task. One for scanning directions. The other for creating nodes and child nodes in the TreeView. Both are easily done with recursive C# functions...

To review, a recursive function is one that calls itself. When scanning directories for a list of files, recursion is useful so the function can scan all files and subdirectories. Subdirectories might have more subdirectories etc.

To list subdirectories in the TreeView, we want to be able to supply a path string such as “C:\Folder1\Folder2\file1.txt” and have the TreeView create nodes and children nodes to match the path. Recursion is then an easy way to add a path to a TreeView control.

Scanning Directories

To scan folders the C# function first needs the root directory. The C# Directory class the two functions we need:  GetDirectories and GetFiles.

Directory.GetDirectories(“C:\\”) //returns an array of paths
Directory.GetFiles(“C:\\”) //returns an array of file paths

The recursive call comes in when the C# function calls itself for each directory in the GetDirectories list.

scanFiles(directories[i]); //For Example

Adding a Path to TreeView

The TreeView control does not handle path strings by default. Here is the layout of the function:

  • If it’s the first call then either create or find the top node.
  • Then, only if there is a backlash ("\"), cut out the first part.
  • Create/Find the node for the first part.
  • Call the function again with the rest of the path.
  • If there was no backlash to begin with, just add it.

The way the function works is that it will keep calling itself with the previous node as reference. The C# function stops when it runs out of backlashes, or parent nodes, to make.

Why so Slow?

If you open of Windows Explorer the file tree comes up in seconds. Why is it then that this tree takes so long to fill?

Windows uses indices and tables to have the file structure ready to go. The way our C# program is doing it is by manually scanning the hard drive and storing the structure of every single file. The downside, it takes very long. The upside, once it is loaded retrieving any part of it is very fast...

Back to C# Article List