Display Directory Structure Using TreeView Control in ASP.NET

Code Below demonstrate how to Display Directory Structure Using TreeView Control in ASP.NET

DirectoryListing.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DirectoryListing.aspx.cs" Inherits="DirectoryListing" %>

<html>
<head id="Head1" runat="server">
    <title>Directory Listing</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <h2>Populating TreeView Nodes On-Demand</h2>

        <asp:TreeView Id="MyTree" 
                      PathSeparator = "|"
                      OnTreeNodePopulate="PopulateNode"
                      ExpandDepth="0"
                      runat="server" ImageSet="XPDirectoryListing" NodeIndent="15">
        
            <SelectedNodeStyle BackColor="#B5B5B5"></SelectedNodeStyle>
            <NodeStyle VerticalPadding="2" Font-Names="Tahoma" Font-Size="8pt" HorizontalPadding="2" ForeColor="#000000"></NodeStyle>
            <HoverNodeStyle Font-Underline="True" ForeColor="#6666AA"></HoverNodeStyle>

            <Nodes>
                <asp:TreeNode Text="Demos" PopulateOnDemand="True" Value="Demos" />
            </Nodes>

        </asp:TreeView>    
    
    </div>
    </form>
</body>
</html>

DirectoryListing.cs
using System;
using System.Data;
using System.IO;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class DirectoryListing : System.Web.UI.Page
{
    protected void PopulateNode(Object source, TreeNodeEventArgs e)
    {
        TreeNode node = e.Node;

        if (e.Node.Value == "Demos")
        {
            e.Node.Value = Server.MapPath("~/");
        }

        String[] dirs = Directory.GetDirectories(node.Value);

        // Enumerate directories
        foreach (String dir in dirs)
        {
            TreeNode newNode = new TreeNode(Path.GetFileName(dir), dir);

            if (Directory.GetFiles(dir).Length > 0 || Directory.GetDirectories(dir).Length > 0)
            {
                newNode.PopulateOnDemand = true;
            }

            node.ChildNodes.Add(newNode);
        }

        // Enumerate files
        String[] files = Directory.GetFiles(node.Value);

        foreach (String file in files)
        {
            TreeNode newNode = new TreeNode(Path.GetFileName(file), file);
            node.ChildNodes.Add(newNode);
        }
    }
}

Popular Posts