The ASP.NET TreeView WebControl documentation includes examples that deal with the basics of the TreeView control, but it's hard to find many examples that show how to load the TreeView using programmatic methods in C#. The examples in this article create a familiar explorer-style tree containing all of the folders and specified files from within a web site, including navigation links from files appearing in the tree. The code presented here illustrates not only some of the TreeView methods and properties, but also a simple recursive method to browse directories and files on a web server.
I originally wrote this code for a client that had a large amount of HTML content organized in folders. This simple technique creates a dynamic tree-styled menu that automatically changes as contributing members add new folders and content files to the site.
The example includes the DocTree.aspx and DocTree.aspx.cs files presented below. The sample code creates the tree starting at this web sites root (shark), so you will see all the .aspx files in my site here at AspAllaiance.
Click to run demo now.
The DocTree.aspx file defines a simple table that contains the unadorned TreeView control on the left, and an <IFRAME> on the right used to show pages from links within the tree (.aspx file links, in this case). The TreeNodeTypes "folder" and "file" could be specified here in the .aspx file, but they are applied within the codebehind page during initialization instead to illustrate these methods. The IFRAME is only here to facilitate the example.
<form id="DocTree" method="post" runat="server">
<table cellpadding="8" cellspacing="0" border="0" height="100%">
<iewc:TreeView id="TreeCtrl" runat="server" SystemImagesPath="/webctrl_client/1_0/treeimages/">
<td valign="top" width="100%" height="100%">
<iframe id="doc" name="doc" frameborder="yes" scrolling="auto" width="100%" height="100%">
We'll start looking at the DocTree.aspx.cs codebehind file's Page_Load method where the TreeView is first initialized. The first task is to create and add two TreeNodeType objects that represent both folders and files. I took a little shortcut here and hard-coded the path to my folder and file images.
After the TreeNodeType objects are added, I make a single call to the GetFolders method passing the root folder of my web site. I use the "~" reference and insure there is a "/" symbol following it. The MapPath method creates the server full path to my virtual directory. You'll see later on that I use the length of this path name to trim the full physical path when creating the TreeNode text and NavigationUrl. The final step here expands the tree a little for the initial viewing.
private void Page_Load(object sender, System.EventArgs e)
if ( ! this.IsPostBack )
// add tree node "type" for folders and files
string imgurl = "/shark/webctrl_client/1_0/Images/";
type = new TreeNodeType();
type.Type = "folder";
type.ImageUrl = imgurl + "folder.gif";
type.ExpandedImageUrl = imgurl + "folderopen.gif";
TreeCtrl.TreeNodeTypes.Add( type );
type = new TreeNodeType();
type.Type = "file";
type.ImageUrl = imgurl + "html.gif";
TreeCtrl.TreeNodeTypes.Add( type );
// start the recursively load from our application root path
// (we add the trailing "/" for a little substring trimming below)
GetFolders( MapPath( "~/./" ), TreeCtrl.Nodes );
// expand 3 levels of the tree
TreeCtrl.ExpandLevel = 3;
All of the directory scanning and loading the TreeView nodes is performed in the recursive method GetFolders. Using the specified path, a string is populated with all of the the folders, and then another string is filled with the files in this path. For each directory in the list, we add a TreeNode object of type "folder", and for each file a node of type "file".
The last step is to look thru all of the nodes we just added, and recursively call GetFolders with the appropriate path and TreeNodeCollection.
private void GetFolders( string path, TreeNodeCollection nodes )
// add nodes for all directories (folders)
string dirs = Directory.GetDirectories( path );
foreach( string p in dirs )
string dp = p.Substring( path.Length );
if ( dp.StartsWith( "_v" ) )
continue; // ignore frontpage (Vermeer Technology) folders
nodes.Add( Node( "", p.Substring( path.Length ), "folder" ) );
// add nodes for all files in this directory (folder)
string files = Directory.GetFiles( path, "*.aspx" );
foreach( string p in files )
nodes.Add( Node( p, p.Substring( path.Length ), "file" ) );
// add all subdirectories for each directory (recursive)
for( int i = 0; i < nodes.Count; i++ )
if ( nodes[ i ].Type == "folder" )
GetFolders( dirs[ i ] + "\\", nodes[i ].Nodes );
The final method (called from GetFolders) creates a TreeNode object from the specified path, node text, and node type. It's a little sleezy, but I use the full path, minus the length of the path that represents my physical "root" path to create the NavigateUrl. This does require that the physical path names match the virtual names in the NavigateUrl (from my root forward).
private TreeNode Node( string path, string text, string type )
TreeNode n = new TreeNode();
n.Type = type;
n.Text = text;
if ( type == "file" )
// strip off the physical application root portion of path
string nav = "/" + path.Substring( MapPath( "/" ).Length );
nav.Replace( '\\', '/' );
n.NavigateUrl = nav;
// set target if using FRAME/IFRAME
Of course, this example has a few shortcuts, and could use some more work before use in a real-world application. However, the example shows some of the powerful System.IO directory and file methods, and the ease with which we can display hierarchical data, even without the more traditional XML used with the TreeView WebControl. As a converted C++ programmer, I prefer these new methods to the old familiar variations on FindFirstFile and FindNextFile. I also find it easy to use the node collections, rather than the familiar parent-child-sibling links used in some of the older Tree controls.
You can download Doctree.zip if you want to use these two files and don't like to type.
Make sure you have the latest download of the Microsoft WebControls and that you have added a Reference to the controls within your application.
Thanks to Dana Coffey, you can now download DirectoryBrowser.zip, a complete Directory Browser sample application written in Visual Basic. The easiest way to use this download is to create a new Visual Basic ASP.NET project with Visual Studio named "DirectoryBrowser". Then unzip the files from this download into the web application folder created by Visual Studio--normally C\:Inetpub\wwwroot\DirectoryBrowser. Be sure and set the application start page to Browser.aspx, and you're ready to go.
You can visit Dana's web site at www.AspForBlondes.com. Many thanks to Dana for this translated download.
Steve Sharrock - www.AspAlliance.com/shark