Tuesday, August 10, 2004

Recursive File List Control (ASP.NET)

This control lists files and folders within a given directory. It shows only the root directories and files, but if you click a folder in the list, your get the sub folders and files.

Control code (filelist.ascx)

<%@ Control Language="C#" %>
<%@ Import Namespace="System.Collections" %>
<script runat="server">

private void Page_Load(object sender, EventArgs e)
{
	// add file types
	fileTypes.Add("doc");
	fileTypes.Add("rtf");
	fileTypes.Add("xls");
	fileTypes.Add("pdf");
	walkFolders(VirtualFolder);
	lnkReset.NavigateUrl = Url;
}
public string VirtualFolder = "/";
private ArrayList fileTypes = new ArrayList();
private ArrayList folders;
private ArrayList Folders {
	get {
		if (folders==null) {
			if (PathInfo!=null) {
				folders = new ArrayList(PathInfo.Split(';'));
			} else {
				folders = new ArrayList();
			}
		}
		return folders;
	}
	set {
		folders = value;
	}
}
private string Url {
	get {
		return HttpContext.Current.Request.Path;
	}
}

private string PathInfo
{
	get {
		return HttpContext.Current.Request.QueryString["show"];
	}
}
private string BuildQuery
{
	get {
		string strList = string.Empty;
		for(int i=0; i<Folders.Count; i++)
		{
			strList += Server.UrlEncode(Folders[i].ToString()) + ";";
		}
		if (strList!=string.Empty) {
			strList = "?show=" + strList.Substring(0, strList.LastIndexOf(';'));
		}
		return strList;
	}
}
private bool InQuery(string s)
{
	for(int i=0; i<Folders.Count; i++)
	{
		if(Folders[i].ToString() == s) {
			return true;
		}
	}
	return false;
}
private bool AllowedFileType(string fileExt)
{
	for(int i=0; i<fileTypes.Count; i++)
	{
		if(fileTypes[i].ToString() == fileExt.ToLower()) {
			return true;
		}
	}
	return false;
}
// based on code from http://groups.google.com/groups?selm=uUvzKryuDHA.540%40tk2msftngp13.phx.gbl&rnum=3
private void walkFolders(string rootPath)
{
	// Open the list
	FileList.Text += "<ul>";
	string mappedRoot = Server.MapPath(rootPath);
	try {
		// Iterate through each folder
		foreach (string folder in System.IO.Directory.GetDirectories(mappedRoot))
		{
			string virtfolder = folder.Replace(mappedRoot, string.Empty);
			string subFolder = rootPath + virtfolder + "/";
			string strList = string.Empty;
			if (InQuery(subFolder)) {
				Folders.Remove(subFolder);
				strList = BuildQuery;
				Folders.Add(subFolder);
			} else {
				Folders.Add(subFolder);
				strList = BuildQuery;
				Folders.Remove(subFolder);
			}
			string b = "<li> Folder: <a href=\"" + Url + strList + "\">" + Server.HtmlEncode(virtfolder) + "</a>";
			FileList.Text += b;
			if (InQuery(subFolder)) {
				// Walk through this folder
				FileList.Text += Environment.NewLine;
				walkFolders(subFolder);
			}
			FileList.Text += "</li>" + Environment.NewLine;
		}	
	} catch (System.Exception ex) {
		Trace.Write(ex.Source + " : " + ex.HelpLink + " : " + ex.Message);
	}
	try {
		// Iterate through the files in this folder
		foreach (string file in System.IO.Directory.GetFiles(mappedRoot))
		{
			string fileName = file.Replace(mappedRoot, string.Empty);
			if (!AllowedFileType(getExt(fileName))) continue;
			// Remove path and prefix with LI
			string b = "<li> File: " + "<a href=\"" + rootPath + fileName + "\">" + Server.HtmlEncode(removeExt(fileName)) + "</a></li>";
			// Put the fileName in the textbox
			FileList.Text += b + Environment.NewLine;
		}
	} catch (System.Exception ex) {
		Trace.Write(ex.Source + " : " + ex.HelpLink + " : " + ex.Message);
	}
	// Close the list
	FileList.Text += "</ul>" + Environment.NewLine;
}

private string removeExt(string fileName)
{
	return fileName.Substring(0,fileName.LastIndexOf('.'));
}

private string getExt(string fileName)
{
	int dot = fileName.LastIndexOf('.') + 1;
	return fileName.Substring(dot, fileName.Length - dot);
}
</script>
<asp:HyperLink id="lnkReset" runat="server" Text="Reset List" />
<asp:Literal EnableViewState="False" runat="server" id="FileList" />

Page code (filelist.aspx)

<%@ Page Language="C#" Trace="False" ContentType="text/html" ResponseEncoding="iso-8859-1" %>
<%@ Register TagPrefix="Files" TagName="List" Src="filelist.ascx" %>
<html>
<head>
<title>File listing</title>
</head>
<body>
<form runat="server">
	<Files:List runat="server" VirtualFolder="/virtualdir/" />
</form>
</body>
</html>

No comments: