ARTICLE

Directory & Files Lister using DirectoryInfo class in Asp.net 2.0

Posted by Munir Shaikh Articles | ASP.NET using VB.NET July 31, 2007
In this article we will see how we can display directories as well files in the browser based explorer, i have tryed to list directories and files even one can browse through inner directories on clicking particular folder, this can be enhanced to actual windows explorer.
Download Files:
 
Reader Level:

The Directory and the DirectoryInfo classes are used to represent a folder in the file system. But there are critical differences between the two. The Directory class has only static methods, and it is used when you need to perform just one operation on a folder. Since you don't have to create an object to represent the directory to perform one operation, all of the methods of the Directory class are static, so you perform the operation without creating an instance of that class

In this article we will be discussing about DirectoryInfo class to list all the directories and files in the directories

The DirectoryInfo class provides information about a given directory which can be set through the constructor while creating the DirectoryInfo object. Once we get a DirectoryInfo object bound to a directory on the file system, we can get any sort of information about it including files it contains. I have included examples of searching for specific files in the directory instead of getting the complete list.

Default.aspx:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<!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>

        <table id="Table1" runat="server" width="100%">

            <tr>

                <td width="30%">

                    <asp:TextBox ID="txtfolder" runat="server"></asp:TextBox>

                </td>

                <td>

                    <asp:Button id="btnSubmit" runat="server" Text="Go!" OnClick="btnSubmit_Click"/>

                    <asp:Label ID="lblMessage" runat="server" Font-Names="Verdana" Font-Size="Small"

                    ForeColor="Red"></asp:Label></td>

            </tr>

        </table>

        <Table id="folderandfiles" runat="server" Width="100%" style="border-style:inset;"  cellpadding="1" cellspacing="1">

         <Tr>

            <Td style="font-family:Verdana;font-size:small;font-weight:bold">Name</Td>           

         </tr>

        </Table>

    </div>

    </form>

</body>

</html>

 

Default.aspx.cs:

 

using System;

using System.Data;

using System.Configuration;

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 _Default : System.Web.UI.Page

{

    string folderPath;

    protected void Page_Load(object sender, EventArgs e)

    {

        if(Request.QueryString.HasKeys())

        {

            folderPath = Request.QueryString["Folder"];

            if (folderPath == null || folderPath == "/")

            {

                folderPath = Request.ApplicationPath.ToString();

            }

            else if (folderPath.EndsWith("/"))

            {

                folderPath = folderPath.Substring(0,folderPath.Length-1);               

            }

            printFolderAndFiles();

        }

    }

    public void printFolderAndFiles()

    {

        string location;

        DirectoryInfo parentDir;

        DirectoryInfo[] childDirs;

        FileInfo[] childFiles;

        try

        {

            parentDir = new DirectoryInfo(folderPath);

            childDirs = parentDir.GetDirectories();

            childFiles = parentDir.GetFiles();

        }

        catch(Exception ex)

        {

            lblMessage.Text = ex.Message;

            return;

        }

        foreach (DirectoryInfo chDir in childDirs)

        {

            HtmlTableRow rowItem = new HtmlTableRow();

            HtmlTableCell cellItemLink = new HtmlTableCell();

            HtmlTableCell cellFolderType = new HtmlTableCell();

            location = folderPath;

            if (location.EndsWith("/"))

            {

                location += chDir.Name;

            }

            else

            {

                location += "/" + chDir.Name;

            }           

            cellItemLink.Controls.Add(new LiteralControl("<a href='Default.aspx?Folder=" + location + "' style='font-family:verdana;font-size:9pt;'> <img src='./Images/folder.gif' border='0'>" + chDir.Name + "</a>"));

            rowItem.Cells.Insert(0, cellItemLink);           

            folderandfiles.Rows.Add(rowItem);

            foreach (FileInfo chFil in childFiles)

            {

                HtmlTableRow rowItemFile = new HtmlTableRow();

                HtmlTableCell cellItemLink1 = new HtmlTableCell();               

                location = folderPath;

                cellItemLink1.Controls.Add(new LiteralControl("<a href='#'><img src='./Images/file.bmp' border='0' font-family:verdana;font-size:9pt;'>" + chFil.Name + "</a>"));

                System.IO.FileInfo file = new FileInfo(Server.MapPat(chFil.Name));               

                rowItemFile.Cells.Insert(0, cellItemLink1);

                folderandfiles.Rows.Add(rowItemFile);

            }

        }       

    }

 

    protected void btnSubmit_Click(object sender, EventArgs e)

    {

        folderPath = txtfolder.Text;

        if (folderPath == null || folderPath == "/")

        {

            folderPath = Request.ApplicationPath.ToString();

        }

        else if(folderPath.EndsWith("/"))

        {

            folderPath = folderPath.Substring(0, folderPath.Length - 1);

        }

        printFolderAndFiles();

    }

}

This article can be extended to fullfledge windows explorer and can be utilized as product for file and directory manager to the hosting companies, who provide customer to upload files and manipulate with the files and folders.

Login to add your contents and source code to this article
share this article :
post comment
 
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Nevron Diagram
Become a Sponsor