[]
In this post, I will show you how to create a File Browser in ASP.NET.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileBrowser.aspx.cs" Inherits="FileBrowser" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1 class="boxes">
Files on the Server:
<asp:Literal ID="litLocation" runat="server" />
</h1>
<asp:Panel ID="panFiles" runat="server" CssClass="boxes">
<asp:PlaceHolder ID="myPlaceHolder" runat="server" />
</asp:Panel>
<asp:Panel ID="Panel1" runat="server" CssClass="boxes">
<asp:TextBox ID="txtFolder" runat="server"></asp:TextBox>
<asp:Button ID="btnNewFolder" runat="server" Text="Create New Folder" OnClick="btnNewFolder_Click" />
</asp:Panel>
<asp:Panel ID="panUpload" runat="server" CssClass="boxes">
Choose a file to upload to the server<br />
<asp:FileUpload ID="fupTest" runat="server" Width="400px" />
<br />
<asp:Button ID="btnUpload" runat="server" Text="Upload File" OnClick="btnUpload_Click" />
<p>
<asp:Label ID="labMessage" runat="server"></asp:Label>
</p>
</asp:Panel>
</div>
</form>
</body>
</html>
using System;
using System.Data;
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;
using System.IO;
public partial class FileBrowser : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string currentRoot = RetrievePathOfFolderToDisplay();
litLocation.Text = currentRoot;
GenerateListing(currentRoot);
}
/// <summary>
/// Displays the content of the specified folder.
/// </summary>
private void GenerateListing(string rootpath)
{
// First clear out the place holder
myPlaceHolder.Controls.Clear();
// Calculate the path to retrieve folders + files
string path = Server.MapPath("") + "/" + rootpath;
// Make the "go up a level" link if needed
MakeUpOneLevelLink(rootpath);
// Get a list of all folders
DirectoryInfo dirInfo = new DirectoryInfo(path);
DirectoryInfo[] folders = dirInfo.GetDirectories();
// Loop through each folder and display it
foreach (DirectoryInfo folder in folders)
{
DisplayFolder(folder, rootpath);
}
// Get a list of all the files in current path
FileInfo[] files = dirInfo.GetFiles();
// Loop through each file
foreach (FileInfo file in files)
{
DisplayFile(file, rootpath);
}
}
/// <summary>
/// Retrieves the path of the folder to be displayed
/// </summary>
///
private string RetrievePathOfFolderToDisplay()
{
string localpath = Request.QueryString["local"];
// If no query string, use uploads folder as the root
if (localpath == null)
return "uploads";
else
// Remove the URL encoding necessary for
// the querystring
return Server.UrlDecode(localpath);
}
/// <summary>
/// Displays the appropriate controls for the passed folder
/// </summary>
private void DisplayFolder(DirectoryInfo folder, string rootpath)
{
// Get the folder name without the path
string shortfolder = Path.GetFileName(folder.FullName);
// Add a folder icon
Image img = new Image();
img.ImageUrl = "images/mime_folder.png";
myPlaceHolder.Controls.Add(img);
// Add a nonbreakable space
LiteralControl space1 = new LiteralControl(" ");
myPlaceHolder.Controls.Add(space1);
// Add a link to the folder so user can display it
HyperLink lnk = new HyperLink();
lnk.Text = shortfolder;
// The link for the folder must pass the folder name.
// Because the folder name may contain characters that are
// not allowed in a querystring, we must URL encode it
lnk.NavigateUrl = "FileBrowser.aspx?local=" +
Server.UrlEncode(rootpath + "/" + shortfolder);
myPlaceHolder.Controls.Add(lnk);
// Add a line break
LiteralControl br1 = new LiteralControl("<br/>");
myPlaceHolder.Controls.Add(br1);
}
/// <summary>
/// Displays the appropriate controls for the passed file
/// </summary>
private void DisplayFile(FileInfo file, string rootpath)
{// Get the filename without the path
string shortname = Path.GetFileName(file.FullName);
// Add a file icon
Image img = new Image();
img.ImageUrl = GetIconForExtension(file);
myPlaceHolder.Controls.Add(img);
// Add a nonbreakable space
LiteralControl space2 = new LiteralControl(" ");
myPlaceHolder.Controls.Add(space2);
// Add a link to the file so user can download/view it
HyperLink lnk = new HyperLink();
lnk.Text = shortname;
lnk.NavigateUrl = Server.UrlDecode(rootpath) + "/" +
shortname;
myPlaceHolder.Controls.Add(lnk);
// Add the file size in kb
long kb = file.Length / 1000;
LiteralControl size = new LiteralControl(" [" + kb +
" KB]");
myPlaceHolder.Controls.Add(size);
// Add a line break
LiteralControl br2 = new LiteralControl("<br/>");
myPlaceHolder.Controls.Add(br2);
}
/// <summary>
/// Returns the filename of the appropriate icon image file
/// based on the extension of the passed file
/// </summary>
private string GetIconForExtension(FileInfo file)
{
string image = "images/";
string ext = Path.GetExtension(file.FullName).ToLower();
if (ext == ".txt")
image += "mime_text.png";
else if (ext == ".doc")
image += "mime_doc.png";
else if (ext == ".pdf")
image += "mime_pdf.png";
else if (ext == ".gif" || ext == ".jpg" || ext == ".wmf")
image += "mime_image.gif";
else if (ext == ".html" || ext == ".htm")
image += "mime_html.gif";
else
image += "mime_unknown.png";
return image;
}
/// <summary>
/// Makes the "go up a level" link (if needed for the
/// current folder) and adds it to the place holder
/// </summary>
private void MakeUpOneLevelLink(string currentFolder)
{
// Get the previous folder (the next one "up" in
// the hierarchy)
string previousFolder = GetPreviousFolder(currentFolder);
// If there is a previous path, add a link to
// place holder
if (previousFolder != "")
{
Image imgBack = new Image();
imgBack.ImageUrl = "images/mime_folder.gif";
myPlaceHolder.Controls.Add(imgBack);
HyperLink lnkBack = new HyperLink();
lnkBack.Text = "..";
lnkBack.NavigateUrl = "FileBrowser.aspx?local=" +
Server.UrlEncode(previousFolder);
myPlaceHolder.Controls.Add(lnkBack);
LiteralControl br = new LiteralControl("<br/>");
myPlaceHolder.Controls.Add(br);
}
}
/// <summary>
/// Gets the previous folder (the next one "up" in the file
/// system hierarchy) from the passed path.
/// If there was no previous folder, return an
/// empty string
/// </summary>
private string GetPreviousFolder(string path)
{
int posOfLastSlash = path.LastIndexOf("/");
if (posOfLastSlash < 0)
return "";
string stripped = path.Remove(posOfLastSlash);
return stripped;
}
/// <summary>
/// Event handler for the upload button for the FileUploader
/// </summary>
protected void btnUpload_Click(object sender, EventArgs e)
{
// The location for the uploaded file is current path
string path = RetrievePathOfFolderToDisplay();
if (fupTest.HasFile)
{
string fullname = Server.MapPath(path + "/" +
fupTest.FileName);
if (System.IO.File.Exists(fullname))
{
labMessage.Text =
"File already exists - uploaded cancelled";
}
else
{
fupTest.SaveAs(fullname);
labMessage.Text = "File successfully uploaded";
// Recreate the file listing to show the
// uploaded file
GenerateListing(path);
}
}
else
{
labMessage.Text = "File was not specified";
}
}
/// <summary>
/// Event handler for the create new folder button
/// </summary>
protected void btnNewFolder_Click(object sender, EventArgs e)
{
// Get the location for the new folder
string folderLocation = RetrievePathOfFolderToDisplay();
string fullPath = Server.MapPath(folderLocation) + "/" +
txtFolder.Text;
// Create the folder on the server
Directory.CreateDirectory(fullPath);
// Recreate the file listing to show the new folder
GenerateListing(folderLocation);
}
}