In a previous article we went over binding XML data to a Datalist. In this
article we are going to bind the contents of a specified directory to a datalist
and display the files.
First in the aspx page we need to place a datalist control. In the following
code, we have an HTML table structure with information about the file. For
example, the name of the file, the size, date created and last modified. Then
we'll add the corresponding properties for the files as they are being displayed
in the datalist. In addition, we also have a call to a function that will
display the appropriate icon next to the file name calls "AddIcon".
<table width="100%">
<tr>
<td></td>
<td class="subhead">File Name</td>
<td class="subhead">File Size</td>
<td class="subhead">Created</td>
<td class="subhead">Last Modified</td>
<td></td>
</tr>
<asp:DataList Runat="server" ID="dlFileList"
RepeatLayout="Flow"
RepeatDirection="Horizontal">
<AlternatingItemStyle BackColor=#6699cc>
</AlternatingItemStyle>
<ItemTemplate>
<tr>
<td align="right">
<asp:ImageButton CommandName="delete"
CommandArgument='<%# DataBinder.Eval(Container.DataItem, "Name")%>'
ImageUrl="~/images/delete.gif"
AlternateText="Delete File"
Runat="server"
ImageAlign="AbsMiddle" Visible='<%#
CheckSecurity %>'></asp:ImageButton>
<asp:Image ImageUrl='<%#
AddIcon(DataBinder.Eval(Container.DataItem, "Name")) %>'
Runat="server" ImageAlign="AbsMiddle" Height="18" Width="18">
</asp:Image>
</td>
<td>
<asp:Label Runat="server" ID="lblFileName" CssClass="normal"><%#
FormatSize(DataBinder.Eval(Container.DataItem, "Name")) %>
</asp:Label>
</td>
<td>
<asp:Label Runat="server" ID="lblSize" CssClass="normal"><%#
FormatSize(DataBinder.Eval(Container.DataItem, "Length")) %>
</asp:Label>
</td>
<td>
<asp:Label Runat="server" ID="Label1" CssClass="normal"><%#
DataBinder.Eval(Container.DataItem, "CreationTime") %>
</asp:Label>
</td>
<td>
<asp:Label Runat="server" ID="lblWrite" CssClass="normal"><%#
DataBinder.Eval(Container.DataItem, "LastWriteTime") %>
</asp:Label>
</td>
<td>
<asp:LinkButton Runat="server" ID="btnDownload"
CommandName="download"
CommandArgument='<%# DataBinder.Eval(Container.DataItem, "Name")%>'
CssClass="normal">Download</asp:LinkButton>
</td>
</tr>
</ItemTemplate>
</asp:DataList>
</table>
In the code behind page we prepare the form above and bind the directory
listings to the datalist by calling the BindFilesToGrid method:
Option Strict On
Imports System.IO
Imports System
Imports System.Web
::
::
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
If Not Page.IsPostBack Then
BindFilesToGrid()
End If
End Sub
Now in the prep form method we'll specify a directory path and get a listing
of all files within the directory and bind the listings to the datalist on our
form.
Private Sub BindFilesToGrid()
'set directory information specific to this portal
Try
Dim strFileNamePath As String = "C:\some directory"
Dim dirInfo As DirectoryInfo = New DirectoryInfo(strFileNamePath)
'now get all files contained in the directory.
Dim aFiles As FileInfo() = dirInfo.GetFiles("*.*")
dlFileList.DataSource = aFiles
dlFileList.DataBind()
Catch ex As Exception
'do some error trapping.
End Try
End Sub
If you remember in our aspx page we had a function called AddIcon. This is
for displaying an appropriate icon next to the file listings in the datalist.
This function accepts a string as input which is the name of the file, then
parses the file extension and checks it against several naming conditions. It
then displays the appropriate icon based on the extension of the file.
Public Function AddIcon(ByVal inFile As String) As String
Dim strExtension As String
If InStr(1, inFile.ToString, ".") <> 0 Then
strExtension = Mid(inFile, InStrRev(inFile, ".") + 1).ToLower
End If
Dim strIconNameAs String
Select Case LCase(strExtension)
Case "bmp", "gif", "jpg", "tif", "jpeg", "tiff"
strIconName= "picture.gif"
Case "doc", "rtf", "xls"
strIconName= "doc.ico"
Case "exe", "bat", "bas", "c", "src"
strIconName= "exe.ico"
Case "htm", "html", "asa", "asp", "cfm", "php3", "inc"
strIconName= "webdoc.ico"
Case "aspx", "cs", "vb", "asmx", "css"
strIconName= "webdoc.ico"
Case "wav", "mp3", "mpg", "avi", "asf", "rm", "mov"
strIconName= "media.ico"
Case "txt", "ini"
strIconName= "text.ico"
Case "zip", "arc", "sit", "rar"
strIconName= "zip.ico"
Case "view"
strIconName= "4.gif"
Case Else
strIconName= "unknown.ico"
End Select
If strIconName <> "" Then
Return "images/" & strIconName
End If
End Function
Now that we have our file names bound to the datalist we can handle events
for the files like downloads, and deletes. Here we handle the item command, we
check the name of the command as defined in the beginning of this article and
handle the command name passed to our method. If this is download we'll download
the file to the user, if it's a delete we'll then delete the file from the
directory and rebind the directory contents to the datalist in order to display
the updated information.
Private Sub dlFileList_ItemCommand(ByVal source As Object, _
ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) _
Handles dlFileList.ItemCommand
Select Case e.CommandName
Case "download"
FileDownload(e.CommandArgument.ToString)
Case "delete"
DeleteFile(e.CommandArgument.ToString)
BindFilesToGrid()
End Select
End Sub
Now lets cover the two methods for downloading the file and deleting the
files from the directory listing. The first one we'll cover is the download of
the file.
Public Sub SecureFileDownload(ByVal inFile As String, _
Optional ByVal strContentType As String = "")
Try
Dim strFileNamePath As String = "C:\some directory"
Dim strExtension As String
strFileNamePath = strFileNamePath & "\" & inFile
Dim myFile As FileInfo = New FileInfo(strFileNamePath)
Response.Clear()
'parse out the extension so we can handle the mime type.
If InStr(1, inFile, ".") <> 0 Then
strExtension = Mid(inFile, InStrRev(inFile, ".") + 1)
End If
'this allows us to either download the file or send it inline
'sending it inline allows us to associate a mime type to the file
'and present it to the user in the browser with associated helper
'application.
If strContentType.Trim = "" Then
strContentType = "application/octet-stream"
Response.AddHeader("Content-Disposition", "attachment;filename=" & _
myFile.Name)
Else
Select Case strExtension
Case "txt" : strContentType = "text/plain"
Case "htm", "html" : strContentType = "text/html"
Case "rtf" : strContentType = "text/richtext"
Case "jpg", "jpeg" : strContentType = "image/jpeg"
Case "gif" : strContentType = "image/gif"
Case "bmp" : strContentType = "image/bmp"
Case "mpg", "mpeg" : strContentType = "video/mpeg"
Case "avi" : strContentType = "video/avi"
Case "pdf" : strContentType = "application/pdf"
Case "doc", "dot" : strContentType = "application/msword"
Case "csv", "xls", "xlt" : strContentType = "application/x-msexcel"
Case Else : strContentType = "application/octet-stream"
End Select
Response.AddHeader("Content-Disposition", "attachment;filename=" & _
myFile.Name)
Response.CacheControl = "public"
End If
'now add the content length of the file and send it in the HTTP headers.
Response.AddHeader("Content-Length", myFile.Length.ToString())
'add the mime type of the file.
Response.ContentType = strContentType
'now stream the file to the browser.
Response.WriteFile(myFile.FullName)
Response.End()
Catch ex As Exception
End Try
End Sub
The other method we use is the ability to delete the files in the directory.
Private Sub DeleteFile(ByVal inFile As String)
Dim strFileNamePath As String
strFileNamePath = "C:\some directory\" & inFile.Trim
If File.Exists(strFileNamePath) Then
File.Delete(strFileNamePath)
End If
End Sub
By: Patrick Santry, Microsoft MVP (ASP/ASP.NET), developer of this site, author of books on Web technologies, and member of the DotNetNuke core development team. If you're interested in the services provided by Patrick, visit his company Website at Santry.com.