Monday, August 10, 2009

Tree view for displaying server root directory

public void PopulateNode(Object source, TreeNodeEventArgs e)
{
TreeNode node = e.Node;
if (node.Value == "Root")
node.Value = "~/";

String rootDirectory = Request.MapPath("~/", Request.ApplicationPath, false);
String fullPath = Request.MapPath(node.Value, Request.ApplicationPath, false);

if (fullPath.StartsWith(rootDirectory) == false)
{
// Mitigate against spoofed callback arguments
// Requested directory is not under root directory
return;
}

String[] dirs = Directory.GetDirectories(fullPath);

// Enumerate directories
foreach (String dir in dirs)
{
String virtualDir = node.Value.TrimEnd(_slashArray) + "/" + Path.GetFileName(dir);

if (!LockFolders.Contains(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;
}

string val = fullPath + @"\" + Path.GetFileName(dir);
val = val.Replace(Server.MapPath(PhysicalPath + "/"), "");
val = val.Replace(@"\", "#");

node.ChildNodes.Add(newNode);


newNode.ImageUrl = "images/folder.gif";
newNode.NavigateUrl = "javascript:getName('" + val + "','1')";
}
}

// Enumerate files
String[] files = Directory.GetFiles(fullPath);
foreach (String file in files)
{
if (!LockFiles.Contains(Path.GetExtension(file)))
{
TreeNode newNode = new TreeNode(Path.GetFileName(file), Path.GetFileName(file));
string val = fullPath + @"\" + Path.GetFileName(file);
val = val.Replace(Server.MapPath(PhysicalPath + "/"), "");
val = val.Replace(@"\", "#");
node.ChildNodes.Add(newNode);
newNode.NavigateUrl = "javascript:getName('" + val + "','0')";
}
}
}

HTML Source Code

No comments: