A File Browser

Using the concepts you've learned so far, it's quite straightforward to put together a simple file-browsing application. Rather than iterating through collections of files and directories manually, this example handles everything using the GridView and some data binding code. Figure 12-1 shows this program in action.

f. Untitled Page - Windows Internet Explorer

HBrsj

k -!-■ -; ~ |gj htt:/jbo«»(tl0a/WtM4FfcftnHV,a*K |X | Pi'

1 tf J g Untied Psoe

: St * 0 Pa3e *

Movs Up I Qrrr^nnV^ivirwDj.Jprej^rW ASF fiFTn VÈ MOBÎpm¿ISWVfT

Name

Sire

Last Modified

Los

7/9/2003 7 :2S:L6 AM

Upload

7/9/2000 7:28:16 AM

File,jpg

631

7/20/2004 Z 15-34 AM

FileBrows =r. as px

3844

7,'S/2Q08 1:06:46 PM

Fil eBrews er. as pü. vb

274-1

7/8/2003 1:07:34 PM

FilsUcloadrna.ascx

724

7/3/2003 1:11 ¡42 PM

File'Jolaadina.aspx.vb

1782.

7/8/2008 5:36:22 PM

folcer.io^

795

7/2072004 1 41 08 AM

EtvlsShaet.css

68

5/27/2005 6:33:40 AM

Us erLa-oc <=r, as p x

928

7/8/2008 5'38'26 PM

Us ErLo ccen as pxvb

2644

7/8/2008 6L29 .56 PM

UserLûccerSerialization.asDx

954

7/8/2008 S'33;42 PM

Ü3ErH5aBerS=riali2ation,a3D>r.vb

4121

7/8/2003 6'4S:L4 PM

Web.confïfl

8136

7/9/20087:28:42 AM

* J Local Intranet 'iilDOTn -

Figure 12-1. Browsingthefilesystem

The directory listing is built using two separate GridView controls, one on top of the other. The topmost GridView shows the directories, and the GridView underneath shows files. The only visible differences to the user are that the directories don't display length information, and they have a folder icon next to their names. The ShowHeader property of the second GridView is set to false so that the two grids blend into each other fairly seamlessly. And because the GridView controls are stacked together, as the list of directories grows, the list of files moves down the page to accommodate it.

Technically, you could handle the directory and file listing using one GridView object. That's because all FileInfo and DirectoryInfo objects have a common parent—the FileSystemInfo object. However, in this grid you want to show the size in bytes of each file, and you want to differentiate the appearance (in this case, through different icons). Because the DirectoryInfo object doesn't provide a Length property, trying to bind to it in a more generic list of FileSystemInfo objects would cause an error.

■ Note This problem has another, equally effective solution. You could create a single GridView but not bind directly to the Filelnfo.Length property. Instead, you would bind to a method in the page class that examines the current data object and return either the length (for FileInfo objects) or a blank string (for DirectoryInfo objects). You could construct a similar method to hand out the correct icon URL.

Here's the declaration for the GridView control that provides the list of directories, without the formatting-specific style properties:

<asp:GridView ID="gridDirList" runat="server" AutoGenerateColumns="False" GridLines="None" CellPadding="0" CellSpacing="l" DataKeyNames="FullName">

<Columns> <asp:TemplateField> <ItemTemplate>

<img src="folder.jpg" alt="Folder" /> </ItemTemplate> </asp:TemplateField>

<asp:ButtonField DataTextField="Name" CommandName="Select" HeaderText="Name" /> <asp:BoundField HeaderText="Size" />

<asp:BoundField DataField="LastWriteTime" HeaderText="Last Modified" /> </Columns> </asp:GridView>

This grid binds to an array of DirectoryInfo objects and displays the Name and LastWriteTime properties. It also creates a Size column, which it doesn't use to display any information—instead, this column simply reserves space so the directory list lines up nicely with the file list that appears immediately underneath. In addition, the DirectoryInfo.FullName property is designated as a key field in the grid so that you can return the full path after the user clicks one of the directories.

You'll also notice that one of the columns doesn't actually display any information—that's the BoundColumn for length that displays header text, but it doesn't link to any data field.

The GridView for the files follows immediately. Here's the slightly shortened control tag:

<asp:GridView ID="gridFilel_ist" runat="server" AutoGenerateColumns="False" Gridl_ines="None" CellPadding="0" CellSpacing="l" DataKeyNames="FullName">

<SelectedRowStyle BackColor="#COfFF" /> <Columns> <asp:TemplateField> <ItemTemplate>

<img src="file.jpg" alt="File" /> </ItemTemplate> </asp:TemplateField>

<asp:ButtonField DataTextField="Name" CommandName="Select" /> <asp:BoundField DataField="Length" /> <asp:BoundField DataField="LastWriteTime" /> </Columns> </asp:GridView>

Note that the GridView for displaying files must define a SelectedRowStyle because it supports file selection. (The GridView for displaying directories handles selection differently. It reacts as soon as a file is clicked by browsing to the new directory and rebinding the controls. Thus, a directory never appears in a selected state.)

The next step is to write the code that fills these controls. The star of the show is a private method named ShowDirectoryContents(), which retrieves the contents of the current folder and binds the two GridView controls. Here's the complete code:

Private Sub ShowDirectoryContents(ByVal path As String) ' Define the current directory. Dim dir As DirectoryInfo = New Directorylnfo(path)

' Get the DirectoryInfo and Filelnfo objects.

Dim files As FileInfo() = dir.GetFiles()

Dim dirs As DirectoryInfo() = dir.GetDirectoriesQ

' Show the directory listing. lblCurrentDir.Text = "Currently showing " + path gridFileList.DataSource = files gridDirList.DataSource = dirs Page.DataBindQ

' Clear any selection. gridFileList.Selectedlndex = -1

' Keep track of the current path. ViewState("CurrentPath") = path End Sub

When the page first loads, it calls this method to show the current application directory:

Protected Sub Page_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then

ShowDirectoryContents(Server.MapPath(".")) End If End Sub

You'll notice that the ShowDirectoryContents() method stores the currently displayed directory in view state. That allows the Move Up button to direct the user to a directory that's one level above the current directory:

Protected Sub cmdUp_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles cmdUp.Click

Dim strPath As String = ViewState("CurrentPath").ToString() strPath = Path.Combine(strPath, "..") strPath = Path.GetFullPath(strPath) ShowDirectoryContents(strPath) End Sub

To move down through the directory hierarchy, the user simply needs to click a directory link. This is raised as a SelectedIndexChanged event. The event handler then displays the new directory:

Protected Sub gridDirList_SelectedIndexChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles gridDirList.SelectedlndexChanged ' Get the selected directory.

Dim dir As String = gridDirList.DataKeys(gridDirList.SelectedIndex).Value

' Now refresh the directory list to ' show the selected directory. ShowDirectoryContents(dir) End Sub

But what happens if a user selects a file from the second GridView? In this case, the code retrieves the full file path, creates a new FileInfo object, and binds it to a FormView control, which uses a template to display several pieces of information about the file. Figure 12-2 shows the result.

f. Untitled Page - Windows Internet Explorer

http://1ocalhost: 1029/VVebsite/FileBrowser.aspx

Move Up J Cw^enfiV show-no D:\Apress >?ro ASP VET3 5 rrr VB ZÖÜS-P'o AS?NET VB200B'\Chapteri2>\Vebsits\\\*bs<te

File: O:\Apress\Pro ASP .NET 3,5 rn VB 2008 \Pro ASP.NET VB200B\Chapterl2 \ Website \ Websi te\f rie. j p g

Created at 7/10/2008 I24l 41 AM Last updated at 7/20/20 0-* 2 15.3^ AM Last accessed at 8/16/2008 1:56.29 AM Archive 631 bytes.

Name

Size

Last Modified

Log

7/9/2008 7 :2S 16 AM

Upload

7/9/2008 7 :28:16 AM

file.ifra

S3i

7/20/2004 2 15 34 AM

Fi 1 eBraws er. as p x

3S44

7/8/2008 1;06:<*5 PM

Fi I eBrows er. as px. iv b

2737

8/16/20 08 1 ;55.22 AM

FileUploaiine.asDv:

724

7/3/2003 Mi-42i>M

FileLlplcadrna.aspx.ub

I ?82

7/8.,r2008 5 '36 22 PM

faldenipc

7 95

7/20/2004 1-41.08 AM

StvleSheet.css

68

5/27/2005 6,33 40 AM

U s erLo 3BEn as pä

928

7/8/2003 5:38:26 PM

U s erLocc er. as ex. t b

2644

7/8'2008 6:29 56 PM

U 3 erLo ccerS eri a 1 iza ti o n. a s px

954

7/8/2008 6 ¡33-42 PM

UserLoccerSerialization.aspx.wb

4121

7/8/2OOS 6 '4S:14 PM

Wieb, tön fis

8136

7/9/2003 7 -2S-4.2 AM

D;\Apress\Pro ASP .NET 3.5 in \/B 2008 ''Pre ASP.NET v'B2008\Chapterl2 ■ w ebsi tfi\w eb s i te'.fi I e,j pg

Figure 12-2. Examiningafile

Here's the code that binds the file information when a file is selected:

Protected Sub gridFileList_SelectedIndexChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles gridFileList.SelectedlndexChanged ' Get the selected file.

Dim file As String = gridFileList.DataKeys(gridFileList.SelectedIndex).Value

' The FormView shows a collection (or list) of items. ' To accomodate this model, you must add the file object ' to a collection of some sort. Dim files As ArrayList = New ArrayListQ files.Add(New Filelnfo(file))

' Now show the selected file. formFileDetails.DataSource = files formFileDetails.DataBind() End Sub

The FormView uses the following template:

<asp:FormView id="formFileDetails" runat="server"> <ItemTemplate> <b>File:

<%# DataBinder.Eval(Container.DataItem, "FullName") %></b><br /> Created at

<%# DataBinder.Eval(Container.DataItem, "CreationTime") %><br />

Last updated at

<%# DataBinder.Eval(Container.DataItem, "LastWriteTime") %><br /> Last accessed at

<%# DataBinder.Eval(Container.DataItem, "LastAccessTime") %><br /> <i><%# DataBinder.Eval(Container.DataItem, "Attributes") %></i><br /> <%# DataBinder.Eval(Container.DataItem, "Length") %> bytes.

<%# GetVersionInfoString(DataBinder.Eval(Container.DataItem, "FullName")) %> </ItemTemplate> </asp:FormView>

The data binding expressions are fairly straightforward. The only one that needs any expression is the GetVersionInfoString() method. This method is coded inside the page class. It creates a new FileVersionInfo object for the file and uses that to extract the version information and product name.

Protected Function GetVersionInfoString(ByVal path As Object) As String

Dim info As FileVersionlnfo = FileVersionInfo.GetVersionInfo(path.ToString()) Return info.FileName + " " + info.FileVersion + "<br>" + _ info.ProductName + " " + info.ProductVersion End Function

Of course, most developers have FTP tools and other utilities that make it easier to manage files on a web server. However, this page provides an excellent example of how to use the .NET file and directory management classes. With a little more work, you could transform it into a full-featured administrative tool for a web application.

0 0

Post a comment

  • Receive news updates via email from this site