Click to See Complete Forum and Search --> : FSO File Listing Problem


Phoenix_1
05-31-2004, 02:10 AM
I want to list all the files within a bunch of subfolders and list them all together in the same page. I have this:

<% Set directory = server.createobject("Scripting.FileSystemObject")
Set listing = directory.GetFolder(Server.MapPath("/dirpath/"))
For Each directoryfile in listing.subfolders
Set listing = directory.GetFolder(Server.MapPath("/dirpath/"&directoryfile.Name))
Next
For Each directoryfile in listing.files %>
<tr>
<td><% =directoryfile.Name %></td>
</tr>
<% Next %>

This works to an extent, but for some reason it ONLY gets the LAST subfolder's files when it should, as far as I know, get all the subfolders' files. Could someone help me out? What am I doing wrong? Thanks in advance.

buntine
05-31-2004, 02:21 AM
This is because you are overwriting the value of the listing object in each iteration of the first for-next loop.
So when it comes time to display each of the sub directories, only the last directory is read from.

To rectify this problem, you will need to nest your loops. So it should look something like this.

<%
Set directory = server.createobject("Scripting.FileSystemObject")
Set listing = directory.GetFolder(Server.MapPath("/dirpath/"))
For Each directoryfile in listing.subfolders
Set listing = directory.GetFolder(Server.MapPath("/dirpath/"&directoryfile.Name))
For Each directoryfile in listing.files %>
With Response
.Write ("<tr>")
.Write ("<td>" & directoryfile.Name & "</td>")
.Write ("</tr>" & vbCrLf)
End With
Next
Next
%>

Its a tad messy, but it should work.

Regards,
Andrew Buntine.

Phoenix_1
05-31-2004, 02:28 AM
Wow that was a fast response! Thank you so much! It's been bugging me all day!

Hmm...doesnt seem to work...it throws an error like so:

Microsoft VBScript compilation error '800a0410'

Invalid 'for' loop control variable


For Each directoryfile in listing.files
---------------------^

buntine
05-31-2004, 02:44 AM
<%
Set directory = server.createobject("Scripting.FileSystemObject")
Set listing = directory.GetFolder(Server.MapPath("/dirpath/"))
For Each directoryfile in listing.subfolders
Set listing = directory.GetFolder(Server.MapPath("/dirpath/"&directoryfile.Name))
For Each dirfile in listing.files
With Response
.Write ("<tr>")
.Write ("<td>" & dirfile.Name & "</td>")
.Write ("</tr>" & vbCrLf)
End With
Next
Next
%>

I named each of the looping variables the same and I had a code terminator in there by accident. Try that.

Phoenix_1
05-31-2004, 11:36 AM
Works like a charm :) Much thanks.