Introduction
This sample project allows users to browse directories via the web. With this code, you can browse these directories via UNC paths or HTTP directory browsing. Example:
- UNC paths - c:\ or \\server\share
- HTTP directory browsing - http://server/directory
Using the code
Create a C# Web Application called Browsing - then drop the files that are in the zip file into that folder. There are 2 helper classes that do all the work that may be removed into their own files and should be applied as a business layer. All the code is kept clean and delineated with #region
s.
Explanation of code blocks
Client side JavaScript
The list box I used is really a DIV
with a border made to look like a list box. There can be images and text, as well as, any other HTML inside the custom list box - something the regular HTML dropdown does not allow. The two JavaScript functions below are called when a row is single clicked or double clicked.
On a single click, the row is highlighted when the HighLight()
method is called. On a double click, the row gets highlighted and sends a request back to the server to update the directories using the DoBrowse()
method.
<script language="javascript">
function DoBrowse(obj, objectName, isDirectory)
{
HighLight(obj, objectName);
if (isDirectory)
{
Form1._actionHidden.value = 'RefreshBrowse';
}
else
{
Form1._actionHidden.value = 'OpenFile';
}
Form1._clickedObjectHidden.value = objectName;
Form1.submit();
}
function HighLight(obj, objectName)
{
var objs = document.all;
for (var i=0; i<objs.length; i++)
{
if (objs[i].className == 'hilite')
{
objs[i].className = 'nohilite';
}
}
obj.className = 'hilite';
}
</script>
ASP.NET code
On a postback, I want to trigger an action - kind of like an event - but I do not have an event driven object. So I created this _actionHidden.Value
that gets set by the JavaScript above and runs through the DoAction()
method.
private void Page_Load(object sender, System.EventArgs e)
{
if(IsPostBack)
DoAction();
}
private void DoAction()
{
switch (_actionHidden.Value)
{
case "RefreshBrowse" :
_browseButton_Click(this, null);
break;
case "OpenFile" :
OpenFile();
break;
}
_actionHidden.Value = "";
}
Fills the list box on a postback with my own HTML table:
private void _browseButton_Click(object sender,
System.Web.UI.ImageClickEventArgs e)
{
if (0 != _browseTextBox.Text.Length)
{
UpdateBrowseTextBoxWithSlash();
_browseTextBox.Text += _clickedObjectHidden.Value;
_clickedObjectHidden.Value = "";
FileList fileList = new FileList(_browseTextBox.Text, "*.*");
Table tb = new Table();
TableRow tr;
TableCell td;
tb.Width = Unit.Percentage(100);
tb.BorderWidth = 0;
tb.CellSpacing = 0;
tb.CellPadding = 4;
foreach (string directory in fileList.Directories)
{
tr = new TableRow();
td = new TableCell();
td.Width = Unit.Percentage(100);
td.CssClass = "nohilite";
System.Web.UI.WebControls.Image directoryImage =
new System.Web.UI.WebControls.Image();
directoryImage.ImageUrl = "Images/folder.gif";
directoryImage.BorderWidth = 0;
directoryImage.ImageAlign = ImageAlign.AbsMiddle;
td.Attributes.Add("onDblClick",
string.Format("DoBrowse(this, '{0}',
true)", directory));
td.Attributes.Add("onClick", "HighLight(this, '')");
td.Controls.Add(directoryImage);
td.Controls.Add(new
LiteralControl("<SPAN class='\"text\"'> "
+ directory + ""));
tr.Cells.Add(td);
tb.Rows.Add(tr);
}
foreach (string file in fileList.Files)
{
tr = new TableRow();
td = new TableCell();
td.Width = Unit.Percentage(100);
td.CssClass = "nohilite";
td.Attributes.Add("onDblClick",
string.Format("DoBrowse(this, '{0}',
false)", file));
td.Attributes.Add("onClick", "HighLight(this, '')");
System.Web.UI.WebControls.Image fileImage =
new System.Web.UI.WebControls.Image();
fileImage.ImageAlign = ImageAlign.AbsMiddle;
fileImage.ImageUrl = "Images/file.gif";
td.Controls.Add(fileImage);
td.Controls.Add(new
LiteralControl("<SPAN class='\"text\"'> " +
file + ""));
tr.Cells.Add(td);
tb.Rows.Add(tr);
}
_browsePlaceholder.Controls.Add(tb);
}
}
Helper Class - FileList
Does all the actual work of getting the ArrayList
of directories and files.
protected void ParseHTTPPage ( string directory, string filter)
{
try
{
string[] filterlist = filter.Split(';');
if (!FileList.IsHTMLContent(directory))
directory = GetPath(directory);
string uristring = ExtractUrifromUrl(directory);
WebClient client = new WebClient();
byte[] pagedata = client.DownloadData(directory);
string[] hrefs = ExtractHrefsFromPage(pagedata);
ArrayList dirs = new ArrayList();
ArrayList files = new ArrayList();
foreach (string uri in hrefs)
{
if (uri.EndsWith("/"))
{
if (uri.StartsWith(uristring))
dirs.Add(uri.Substring(uristring.Length).Trim('/'));
}
else
{
string file = Path.GetFileName(uri);
foreach (string query in filterlist)
{
if (System.Text.RegularExpressions.Regex.IsMatch(file,
"." + query.Replace(".", "\\."),
RegexOptions.IgnoreCase))
{
files.Add(file);
break;
}
}
}
}
_directories = new string[dirs.Count];
dirs.CopyTo(_directories);
System.Array.Sort(_directories);
_files = new string[files.Count];
files.CopyTo(_files);
System.Array.Sort(_files);
_basedirectory = directory;
if (!_basedirectory.EndsWith("/"))
_basedirectory += "/";
}
catch(Exception except)
{
System.Diagnostics.Trace.WriteLine("Exception" +
" parsing URL: " + except.Message);
}
return;
}
protected void PasreUNCPage ( string directory, string filter)
{
try
{
if (FileAttributes.Directory !=
(FileAttributes.Directory &
File.GetAttributes(directory)))
directory = GetPath(directory);
}
catch(Exception)
{
return;
}
try
{
_directories =
RelativePaths( Directory.GetDirectories(directory, "*.*"));
System.Array.Sort(_directories);
}
catch(Exception except)
{
System.Diagnostics.Trace.WriteLine("Exception" +
" parsing directory: " + except.Message);
}
try
{
_files = new string[0];
string[] extensions = filter.Split(';');
foreach (string ext in extensions)
{
string[] foundfiles =
RelativePaths( Directory.GetFiles(directory, ext));
if (foundfiles.Length > 0)
{
string[] newlist = new string[_files.Length
+ foundfiles.Length];
_files.CopyTo(newlist, 0);
foundfiles.CopyTo(newlist, _files.Length);
_files = newlist;
System.Array.Sort(_files);
}
}
}
catch(Exception except)
{
System.Diagnostics.Trace.WriteLine("Exception" +
" parsing files: " + except.Message);
}
_basedirectory = directory;
if (!_basedirectory.EndsWith("\\"))
_basedirectory += "\\";
return;
}
Helper Class - PathHelper
Does any of the path handling functions.
Points of Interest
Check out more code samples and components here.
History
Date posted: July 14, 2004.