This script shows how to read a directory structure in ASP. The display belowshows the contents of a few directories located on this site, including anysubdirectories and their contents.
Each file is displayed as a link, so you can click on the file name to viewthat particular file.
How it Works
The script makes use of the FileScriptingObject which allows you to accessfiles and directories on the server. These objects contain properties thatdescribe the file or folder name, physical path, size, last modified date andother information.
Folder objects also contain collections of other FileScriptObjects for eachsubfolder and file in that directory.
The ListFolderContents subroutine does the work. It requires thephysical path to the folder, which can be found using the built-in Server.MapPath() function. This function takes either a relative orabsolute URL and returns the physical path to that file. For example, the URL"/graphics/image.gif" might return a path of "D:Inetpubwwwrootgraphicsimage.path". Either directories or files can beused.
Using Recursion
ListFolderContents first creates a Folder object using the given path. It displays the folder name then loops through the SubFolders collection ofthat folder. For each subfolder it makes a recursive call to itself, passingthe subfolder path.
This causes it to walk down through the hierarchial directory structure anddisplay each subfolder and contents. The recursion stops down each branch whenit reaches a subfolder that has no subfolders of it's own.
Mapping a Physical Path to a URL
After listing all subfolders, ListFolderContents then loops through theFiles collection, displaying each file name to complete the contents displayfor the given folder.
Each file is displayed as a standard HTML link. Unfortunately the Server.MapPath() function has no compliment to convert a physical pathback to a URL. But this is not difficult to do and the script includes afunction called MapURL that takes the file path and returns a valid URLthat can be used to link to it.
Notes on the Example
To list the entire site structure you could simply call ListFolderContents once with path to the web site root at the argument.
For the example on this page however, only a few subdirectories are used. Otherwise the display would be several pages long. So separate calls are madefor each subdirectory to be shown.