Register | Login
Friday, July 04, 2008

Sections
  
About Us
  
Hosting Provided by Server Intellect
Partners
Downloads
  
 WWWCoder.com Resource Directory

Binding the Contents of a Directory to a Datalist
10/18/2003 8:17:11 PM

In this article we will create a directory browser by by binding the contents of a directory to a datalist. We also provide file downloading and delete methods in this article.

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.

Related Articles
   Related Document Adding Attributes to an Object Within a Datalist
   Related Document Bind a Datalist to a Remote XML File


Page Options:
format for printing  Format for Printer
email article  Email Page
add to your favorites   Add to Favorites
How would you rate the quality of this content?
Poor - - Excellent
Comments?
Overall Rating:
Comments Left:
Left on 5/30/2005 5:29:57 AM by Anonymous
Comments: mmm no complete source code ? no comments ? --> Bad sample
Left on 5/17/2005 12:44:08 PM by Anonymous
Comments: With minor edits and some of my own icons I have made this work with the exception of the file download. If I leave off the function (dlFileList_ItemCommand) all the rest works. With in in, I get BC30506: Handles clause requires a WithEvents variable.

No ratings available.
Left on 3/15/2005 3:27:22 AM by Anonymous
Comments: I'm having problem in usind onItemCommand for getting details in the form of a datagrid. Please can you help!!!!!!!!
Left on 2/24/2004 8:29:52 AM by Anonymous
Comments: I am impressed with the way , this article is written by the author.
Excellent Article.
Left on 2/18/2004 8:26:36 AM by Anonymous
Comments: Hooking up Command/controls to the Item_Command Event Is killing me....OnItem_Command  Item_Command  ..?? This is really easy but I'm stil missing something.... ? ? Delegate to get my controls click to _Item_Command ??? I've seen datalists declared in codebehinds witevents to expose the Item_Command.... I dont believe this is required for C# so Should I += a new event handler theres gotta be an easy little demo for this.....
Left on 1/20/2004 4:28:45 PM by Anonymous
Comments: how do you get the icons?
Left on 11/7/2003 11:13:32 PM by Anonymous
Comments: incomplete
Left on 11/5/2003 6:30:42 AM by Anonymous
Comments: The CheckSecurity function is there for you to check and see if the user is allowed to delete the file. Since all security systems are different I didn't elaborate on it.
No ratings available.
Left on 11/5/2003 3:14:55 AM by Anonymous
Comments: Is there any way of checking the accessability of file to the user before binding it to the Datalist?
Left on 11/5/2003 2:40:40 AM by Anonymous
Comments: How do i can use this

CommandArgument='<%# DataBinder.Eval(Container.DataItem, "Name")%>'
ImageUrl="~/images/delete.gif"
AlternateText="Delete File"
Runat="server"
ImageAlign="AbsMiddle" Visible='<%#
CheckSecurity %>'>


because error happened. at
"CheckSecurity"
and other

<%#
FormatSize(DataBinder.Eval(Container.DataItem, "Length")) %>


Left on 11/2/2003 6:42:38 PM by Anonymous
Comments: Where can I find icons?
  

 Latest Articles
  

 Latest News
  

 

Spotlight
Syndication

 


 


Digg This
 


DotNetNuke Platinum Benefactor

  
 

 Terms Of Use | Privacy Statement
 Copyright 2008 - Santry Technology Solutions, Box 172, Girard, PA 16417, (814) 774-0970