<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="OnDemandFiles" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="TreeView1" OnTreeNodePopulate="PopulateNode" runat="server" ExpandDepth="0">
<Nodes>
<asp:TreeNode PopulateOnDemand="True" Text="Demos" Value="Demos"></asp:TreeNode>
</Nodes>
</asp:TreeView>
</div>
</form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Collections;
using System.Data;
using System.Data.Common;
using System.Configuration;
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;
using System.IO;
public partial class OnDemandFiles : System.Web.UI.Page
{
static readonly char[] _slashArray = new char[] { '/' };
protected void PopulateNode(Object source, TreeNodeEventArgs e)
{
TreeNode node = e.Node;
if (node.Value == "Demos")
node.Value = "~/";
String rootDirectory = Request.MapPath("~/", Request.ApplicationPath, false);
String fullPath = Request.MapPath(node.Value, Request.ApplicationPath, false);
if (fullPath.StartsWith(rootDirectory) == false)
{
return;
}
String[] dirs = Directory.GetDirectories(fullPath);
foreach (String dir in dirs)
{
String virtualDir = node.Value.TrimEnd(_slashArray) + "/" + Path.GetFileName(dir);
TreeNode newNode = new TreeNode(Path.GetFileName(dir), virtualDir);
if (Directory.GetFiles(dir).Length > 0
|| Directory.GetDirectories(dir).Length > 0)
{
newNode.PopulateOnDemand = true;
}
node.ChildNodes.Add(newNode);
}
String[] files = Directory.GetFiles(fullPath);
foreach (String file in files)
{
TreeNode newNode = new TreeNode(Path.GetFileName(file), Path.GetFileName(file));
node.ChildNodes.Add(newNode);
}
}
}