Search code examples
javascriptasp-classic

How to loop or access Object Collection in ASP Classic (javascript)?


So I found this old web application (asp classic) in my workplace and been asked to modified it. What i'm trying to do is, I want to display all files from this particular folder. Instead of hardcoding each of the file name with its link, I tried as below:

<%
    var fs = new ActiveXObject("Scripting.FileSystemObject");
    var fo = new ActiveXObject("Scripting.FileSystemObject");
    var f = new ActiveXObject("Scripting.FileSystemObject");
    var theFile = new ActiveXObject("Scripting.FileSystemObject");

    fo=fs.GetFolder("C:\\inetpub\\wwwroot\\edocument\\MyFiles");
    f = fo.Files;

    For Each theFile in f
        Response.write(theFile.Name+"<br>");
    Next
%>

seems like For Each loop won't work/not recognized in asp javascript but found some working example using vbscript. I also tried to access the collection directly:

 Response.write(f[0].Name);

but it says ...is null or not an object

Any idea how can I access this Files Collection?


Solution

  • In javascript you need an Enumerator() to walk the collection, and either use for next, or while like in the example below

    <% @LANGUAGE="JScript" %>
    <%
    var fso = Server.CreateObject("Scripting.FileSystemObject");
    var fo = fso.GetFolder("C:\\inetpub\\wwwroot\\edocument\\MyFiles");
    
    var f = new Enumerator(fo.Files);
    f.moveFirst()
    while (!f.atEnd()) {
       Response.Write(f.item().name + "<BR>");
       f.moveNext();
    }
    
    fo = null;
    f = null;
    fso = null;
    %>