When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles [1.x] [2.0]
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
Headlines from ASPWire.com
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML
Information:
Advertise
Feedback
Author an Article
Jobs
















internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers
ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs
Print this Page!

Windows Systems Administrator
Jupitermedia
US-CT-Darien

Justtechjobs.com Post A Job | Post A Resume

Published: Wednesday, May 28, 2003

Displaying the Files in a Directory using a DataGrid
By Scott Mitchell


Introduction
There are many scenarios Web developers face where they need to be able to display information about the Web server's file system. For example, a Web hosting company might want to provide a "Control Panel" that allows their clients to edit their Web site's files using a Web interface. A developer working on her company's intranet might want to create a Web page that provides a nice listing of business reports that reside in an intranet-accessible directory.

- continued -

In classic ASP, to access the Web server's file system developers used the FileSystemObject library. (For more on the FileSystemObject library check out the FileSystemObject FAQ Category at ASPFAQs.com.) In .NET, there is a set of classes in the System.IO namespace that allow for programmatic access to the file system.

Accessing file system information in ASP.NET is about as easy (if not easier) as it was in classic ASP. The real benefit with ASP.NET comes in displaying the file system information. As we will see in this article, the file system information can be bound to any of the data Web controls, such as the DataGrid, DataList, or Repeater. This means that the information can be displaying in an aesthetically-pleasing manner with minimal time.

Examining Accessing the File System Using ASP.NET
The .NET Framework contains two classes for accessing directory information, and two classes for accessing file information. To access directory information, use either the Directory or the DirectoryInfo class; to access file information, use either the File class or the FileInfo class.

The differences between the two classes is the level of information it returns and how it is used. The Directory and File classes are static classes, meaning that you don't have to create an instance of the class in order to use its methods. These classes are useful if you want to quickly perform some directory-related function. For example, to delete a file, you can use File.Delete(filePath); to determine if a directory exists, you can use Directory.Exists(directoryPath).

The Info classes - FileInfo and DirectoryInfo - require that you first create an instance of the class and specify the file or directory's name in the constructor. For example, to delete a file using the FileInfo class, you'd use the following code:

Dim myFile as FileInfo = New FileInfo(filePath)
myFile.Delete()

Getting a List of Files in a Directory
Both the Directory and DirectoryInfo classes contain a method to get all of the files in a directory (or to get all of the files in a directory matching some wildcard expression, like *.htm) - this method is called GetFiles() and is used as follows:

' --- Directory Example ----
Dim files() as String = Directory.GetFiles(directoryPath[, optionalWildCard])

' --- DirectoryInfo Example ----
Dim myDir as DirectoryInfo = New DirectoryInfo(directoryPath)
Dim fileInfos() as FileInfo = myDir.GetFiles([optionalWildCard])

As you can see, the Directory.GetFiles() method accepts one or two parameters. You must specify the path of the directory whose files you want to get, and you may optionally specify a wildcard path (like *.aspx). This method returns a String array, which contains the filenames in the directory (that match the wildcard expression, if supplied). The DirectoryInfo.GetFiles() method doesn't accept a directory path input since the directory's path is already known. Unlike the Directory.GetFiles() method, the DirectoryInfo.GetFiles() method returns an array of FileInfo objects, not Strings.

Displaying a Directory's Files in a DataGrid
To display a directory's files in a DataGrid (or DataList or Repeater) all we need to do is assign the String array or FileInfo array to the DataGrid's DataSource property and then call the DataGrid's DataBind() method. For this example, we'll use the DirectoryInfo.GetFiles() method instead of the Directory.GetFiles() method. If we opted to use the Directory.GetFiles() method then all we'd be able to show in the DataGrid is the file's name. By using the DirectoryInfo.GetFiles() method instead, we can display other attributes of the file, such as its size, last modified date, and so on.

<%@ Import Namespace="System.IO" %>
<script language="VB" runat="server">
  Sub Page_Load(sender as Object, e as EventArgs)
    Dim dirInfo as New DirectoryInfo(Server.MapPath(""))
    
    articleList.DataSource = dirInfo.GetFiles("*.aspx")
    articleList.DataBind()
  End Sub
</script>

<asp:DataGrid runat="server" id="articleList" Font-Name="Verdana"
    AutoGenerateColumns="False" AlternatingItemStyle-BackColor="#eeeeee"
    HeaderStyle-BackColor="Navy" HeaderStyle-ForeColor="White"
    HeaderStyle-Font-Size="15pt" HeaderStyle-Font-Bold="True">
  <Columns>
    <asp:HyperLinkColumn DataNavigateUrlField="Name" DataTextField="Name" 
           HeaderText="File Name" />
    <asp:BoundColumn DataField="LastWriteTime" HeaderText="Last Write Time"
        ItemStyle-HorizontalAlign="Center" DataFormatString="{0:d}" />
    <asp:BoundColumn DataField="Length" HeaderText="File Size"
		ItemStyle-HorizontalAlign="Right" 
		DataFormatString="{0:#,### bytes}" />
  </Columns>
</asp:DataGrid>  
  
[View a Live Demo!]

As the above code sample shows, all that it takes to bind the list of files in a directory to an ASP.NET DataGrid is simply setting the DataGrid's DataSource to the result of the GetFiles() method. Specifically, in the above code sample the list of files with the extension .aspx that reside in the same directory that the ASP.NET Web page itself resides in are displayed.

Particular attributes of the FileInfo class can be displayed in the various DataGrid columns by simply setting the column's properties accordingly. For example, the FileInfo.Length property is displayed in the last BoundColumn by setting the BoundColumn's DataField property to Length. (For a full list of FileInfo properties, see the technical documentation.)

Now that we've seen how to simply display the list of files in a directory, let's look at making the example a bit more useful by allowing users to delete a file with the click of a button. We'll see how to accomplish this in Part 2.

  • Read Part 2!


    Windows Internet Technology | ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article



  • JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
    Microsoft Article: 7.0, Microsoft's Lucky Version?
    Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Windows Server 2008
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES