ASP Tutorials - Listing the files in a folder with the File System Object
The File System Object contains some powerful functionality allowing an ASP script to list files in a directory, as well as other functions described elsewhere.
The File System Object contains some powerful functionality allowing an ASP script to list files in a directory, as well as other functions described elsewhere.
To list all the files in a folder using classic ASP, use the File System Object. First create an instance of the File System Object, then obtain a folder. This contains a Files property which is a collection and can be used in a For..Each loop.
Set FSO = Server.CreateObject("Scripting.FileSystemObject")
Set AFolder = FSO.GetFolder(Server.MapPath("."))
For Each Item in AFolder.Files
Response.Write Item & "<br>"
Next
In this example the folder that has its contents listed is the one containing the script, and its physical path is found using Server.MapPath. In most cases it would probably be a different folder and its path could be found using Server.MapPath or it could be hard coded, for example:
Set AFolder = FSO.GetFolder(Server.MapPath("c:\uploads"))
This would list the contents of a directory on the server called "c:\uploads\". It must always be a physical path and not a relative path.
The above example can be modified to use some string manipulation and conditional logic to only list files with a certain extension.
ExtensionAllowed = "asp"
Set FSO = Server.CreateObject("Scripting.FileSystemObject")
Set AFolder = FSO.GetFolder(Server.MapPath("."))
For Each Item in AFolder.Files
TempArray = Split(Item, ".")
Extension = TempArray(UBound(TempArray))
If UCase(Extension) = UCase(ExtensionAllowed) Then
Response.Write Item & "<br>"
End If
Next
The extension to list is set in the first line although this could be coded straight into the IF statement. The extension is found by using the Split function with the dot character as a delimiter. The last entry in the array produced by Split will be the extension of the file, and the index of this item is found with the UBound function. When the strings are compared they are both converted to upper case to ensure that there is a match for uper and lower case file names.
The method of extracting the file extension could be used to extract the file name by using the backslash character as a delimiter in the Split function. The last entry in the array would be the file name.
The sample code in these tutorials is written for VBScript in classic ASP unless otherwise stated. The code samples can be freely copied.
© Chestysoft, 2024.