Click here to Skip to main content
Click here to Skip to main content

Browsing Via Directories or HTTP, with ASP.NET

, 14 Jul 2004
Rate this:
Please Sign up or sign in to vote.
An article on browsing via directories or HTTP, with ASP.NET.

Sample Image - Browsing.gif

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 #regions.

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("/"))
            {
                //    handle the directory
                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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Bobby Ryzhy
Web Developer
United States United States
Masters Degree in Computer Science - emphasis on Database design. Been a contract software engineer for the past 10 years.

Comments and Discussions

 
GeneralManipulation Pinmemberdansoft26-Mar-06 1:35 
GeneralWorks as Advertised... Pinmembercode-frog3-Mar-06 5:31 
GeneralError while browsing network share Pinmemberasaxena1120-Jul-05 6:51 
GeneralBrowsing.asp in VB.net language PinmemberGuntram Sartoris25-May-05 5:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140827.1 | Last Updated 15 Jul 2004
Article Copyright 2004 by Bobby Ryzhy
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid