views:

319

answers:

2

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?

A: 

No, but you can enumerate them and track the index yourself:

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

i = 0
For Each oFile In oFiles
   Response.Write i & " = " & oFile.Name
   i = i + 1
Next
Mark Brackett
Yeah, the loop is easy to do, but if you just want to grab the first one and use it straight away.....?!
Magnus Smith
+2  A: 

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.

dpmattingly
I thought (in general) that collections could be accessed randomly by item bumber? Sadly this article doesnt mention FileSystemObject - http://msdn.microsoft.com/en-us/library/ms525228.aspx
Magnus Smith
In general, collections can be accessed via index numbering, but the Files Collection is not a normal collection. It does have an item property, but it appears that the key that it uses is filename. c.f. http://www.devguru.com/Technologies/vbscript/quickref/filescoll_item.html
dpmattingly