Search code examples
collectionsasp-classicfilesystemobject

ASP FileSystemObject collection cannot be accessed by index


Am I going mad? I cannot find a way to get hold of the first file in a folder with the FileSystemObject (classic ASP). With most collections you'd think the index 0 or 1 might work, but IIS says "Invalid procedure call or argument".

Neither of these last 2 lines work:

Set oFileScripting = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFileScripting.GetFolder(sFolder)
Set oFiles = oFolder.Files
If oFiles.Count = 0 Then Response.Write "no files"
Response.Write oFiles(0).Name
Response.Write oFiles.Item(1).Name

Am I being mega-stupid, or is there no way to use an index to access this particular collection?


Solution

  • The Files Collection is not an Array, and does not contain random-access functionality. If you absolutely need this functionality, the closest thing to imitate it would be to iterate through the folder and create a new Array containing the names of the files found, use this new array as the random-access source, and create File objects from the Array values.

    ReDim FileArray(oFiles.Count)
    
    i = 0
    For Each oFile In oFiles
       FileArray(i) = oFile.Name
       i = i + 1
    Next
    
    Set oFile = oFileScripting.GetFile(sFolder + "\" + FileArray(0))
    

    I certainly wouldn't recommend this if it is at all avoidable.