Friday, 8 October 2010

ASP: Scripting.FileSystemObject... show folder content

   


This is the last post of the Scripting.FileSystemObject series. After seeing how to manipulate files and folders, how to upload files and how to get file information, I would like to show how to retrieve a folder's content. This is probably the most easy thing to do, and as usual we start by setting the variables and the object:
<%
Dim FSO
   Set FSO = Server.CreateObject("Scripting.FileSystemObject")
   Dim folderpath
   folderpath = Server.MapPath(yourfolder)
Change yourfolder with something like "/doc/". Then we get the content:
Set fileinfo = FSO.GetFolder(folderpath)
%>
We can show the content with:
<table width="100%" border="1">
<%For each filefound in fileinfo.Files
%>
<tr><td><%=filefound.Name%></td></tr>
<%Next%>
</table>
All the files in the folder are now displayed in a table. You can add different information on the file, for example the size: just add a new <td> and use the size method. Change the <tr><td>... line with:
<tr><td><%=filefound.Name%></td><td><%=filefound.Size%></td></tr>
And so on...
If you want to make the file name clickable, replace the above line with:
<tr><td><a href="<%=Replace(folderpath,"/","")&"/"&filefound.Name%>"><%=filefound.Name%></a></td><td><%=filefound.Size%></td></tr>
As a side note on file size, you could add a little if... then.. else clause to make the size more readable:
 if Clng(filefound.Size) < 1024 then
      VarSize = filefound.Size & " bytes"
 else
      VarSize = Clng(filefound.Size / 1024) & " KB"
 end if
Afterwards replace <%=filefound.Size%> in your table with <%=VarSize%>.
As you can see you can play around with all the information and manipulate them according to your needs.
Related posts:
ASP: Scripting.FileSystemObject... how to read file or folder information
JQuery: 5 useful file upload plugins
ASP: Scripting.FileSystemObject... how to move, copy and delete a file or a folder

2 comments:

  1. Thank you Marco. I found the filesystem posts really useful!
    Keep up the good work!

    Steve

    ReplyDelete
  2. Thank to you, Steve. You are actually the first to comment and to share thoughts. I really appreciate it!

    ReplyDelete

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.