Blue Theme Orange Theme Green Theme Red Theme
 
Mindcracker MVP Summit 2012
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » ASP.NET and Web » Directory & Files Lister using DirectoryInfo class in Asp.net 2.0

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

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.

Author Rank :
Page Views : 17413
Downloads : 201
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
FileManager.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

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.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Munir Shaikh
Munir is MCP in Microsoft .NET Framework 3.5, Windows Communication Foundation
Appl ication Developmen, software Developer/ project lead with 9 Yrs development experience who works on IT projects mainly for Microsoft and some open source technologies. Most of these projects have been intranet based web applications / sites with SQL/Oracle as back-end. Currently he  is focusing more on Silverlight, WCF & WPF development. He had worked on payment gateway implementation. He is experienced in Insurance, Supply Chain management, Trading, Real-Estate & currently Legacy modernization domain.
Apart from this he has implemented on CMMi L3 for organization and has good understanding of process. He has also involved in consulting activities like Architecture Review, Project Plan, HLD, LLD, Risk Management etc....
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
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.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
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!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.