Enumerating Filesystem Object


    I have written a web application that allows a user to log files that they have transferred. The main issue is that it is restricted to choosing files from one particular folder because they have to justify their transfers and log the security aspects of the files. There is a group that needs the ability to pick a folder and then get all the files from this folder and the subsequent subfolders into a single list while still including the path for each folder. I tried to find an easier way to do this, but have ran into a snag. Any help or pointers to help would be appreciated.

Who is Participating?

Improve company productivity with a Business Account.Sign Up

DanRollinsConnect With a Mentor Commented:
Here you go!  This is a fully functional HTA that provides the code you need plus demonstrates how to use it.  Just copy the following and paste it into a file named Tester.HTA. Then double-click that file.

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- start of file Tester.HTA
<input type=button value="reload (if you edit the script)" onclick= "document.location.reload();">
<input type=button onclick="DoTest();" value="Do Test">
Results will go here:
<table border=2><TR><TD>
      <div id="stResults"><br></div>

var goFSO= new ActiveXObject("Scripting.FileSystemObject");

// populates Array asResult
function GetAllFilesInFolder( sStartingFolder, asResult )
      oFldr= goFSO.GetFolder( sStartingFolder );
      var eFile= new Enumerator( oFldr.Files );
      for (; !eFile.atEnd(); eFile.moveNext() ) {
            var s= eFile.item();
            asResult.push( s );
      var eFldr= new Enumerator( oFldr.SubFolders );
      for (; !eFldr.atEnd(); eFldr.moveNext() ) {
            var s= eFldr.item();
            GetAllFilesInFolder( s, asResult );

function DoTest()
      asAllFiles= new Array();

      GetAllFilesInFolder( "c:\\temp\\", asAllFiles );

      //----- the demo is over.  This is just to show the data in the array
      var s="";
      for ( var j=0; j<asAllFiles.length; j++ ) {
            s+= asAllFiles[j] + "<br>";       
      document.all.stResults.innerHTML= s;
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- end of file Tester.HTA

The function of interest is
       GetAllFilesInFolder( sStartingFolder, asResult )
which is recursive, so it's kind of fun to play with.  It adds each file to the Array, then looks at each folder and *calls itself* for each one. SWEET!   The result is that asResult ends up holding a list of fully-qualified filenames of all files in the specified folder plus all files in each folder that's in that folder, and so forth.

Later, if you need to split out the folder from the filename, just use (for instance)

   var oFile= goFSO.GetFile( asAllFiles[17] );
   var sNameAndExt= oFile.Name;          // eg:   filename.ext
   var sFldrPath=      oFile.ParentFolder; // eg:   c:\temp\mystuff

-- Dan
Is this an ASP question?  (it can't be done in JavaScript)
It *can* be done using the FileSystemObject ActiveX object.

It seems pretty straight forward to enumerate the files and directories (and their files, etc..) and generate a list.  With what part are you having trouble?

-- Dan
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

robotman757Author Commented:
I am able to get one folder and get all the files in that folder and then pass the files into a listbox control. I pass the folder name through a single variable. What I want to do is start at this folder and get all files in it and then go to a subfolder and get any files and subfolders. I need to keep the full path to the file, and it has to store the path and filename in 2 seperate fields in the underlying Access database. I can't seem to find a way to get this to work.
var a = yourVariable.match(/(.+\/)([^\/]+)$/);

path = a[1];

fileName = a[2];
robotman757Author Commented:
Here is the code that I currently use to get a single folder with the files. It is ran when a user presses a button.

function getfiles()

     var pShell = new ActiveXObject("Shell.Application");
     var pFolder = new Object;                              
         pFolder = pShell.BrowseForFolder(0, "Choose a folder", 0);      
         if (pFolder == null)
          alert("You must choose a folder.");
          document.location.href="usrmadd2.asp?UserID=<% =uid %>";
     var pFolderItem = new Object;            
         pFolderItem = pFolder.Items().Item();
         document.Form1.SelFldr.innerText = pFolderItem.Path;
         //Ensure there are no options in ListBox if ran again
         if (i!=0){
         for (var z=document.Form1.ListBox1.options.length-1; z>=0; z--)
             document.Form1.ListBox1.options[z] = null;
         numpass = 0;}
     var fso = new ActiveXObject("Scripting.FileSystemObject");
     var sFolder = new Object;
          i = 0;
          fldrfiles=new Array();
          var sFile = new Enumerator(sFolder.Files);
           for (; !sFile.atEnd(); sFile.moveNext())
            ss = sFile.item();
            tmpfile = new String(ss.name);
            fldrfiles[fldrfiles.length] = new Option(tmpfile, i);
            //alert(fldrfiles[2].text + fldrfiles[2].value);
            for (var y = 0; y < fldrfiles.length; y++)
             var options = new Object;
              document.Form1.ListBox1.options[y] = new Option (fldrfiles[y].text , fldrfiles[y].value);
var a,i,path=[],fileName=[];
for (i=0;i<document.Form1.ListBox1.options.length;i++){
  a = document.Form1.ListBox1.options[i].text.match(/(.+\/)([^\/]+)$/);
  path = a[1];
  fileName = a[2];

It might be   a = document.Form1.ListBox1.options[i].value, I'm not sure.
I don't understadn th part about the listbox and I believe the part about stroing data into an Access database is a separate issue.

The simplest solution involves calling a short routine that generates the fully-qualified pathname of every file that is in this directory or any child directory; that is

Directory name (String) =

Filename list (Array) =

I can write code that will do that for you.  Will that help?  Will you be able to figure out how to look at each item and store it in a desired way into your database?

-- Dan
robotman757Author Commented:
The whole program uses the list of files and for each file has to store the name of the file along with about 18 other pieces of information including the path. What I did was create a button to get the folder and then list all the files so that a user could then select the files they need which then moved them to another listbox. From that page they go to another area where the user decides what the security level is and where the file is going to be saved to. Then it has to go to a dynamically created page that does more stuff. This all works fine if it is getting files from one folder. The code I posted does that well. If you can write code that can go into each subfolder and get all that info, that would be great. I will find a way to pass the information to the next few pages.

Dan (My name too!)
>> each file has to store the name of the file along with about 18 other pieces of information...
>> If you can write code that can go into each subfolder and get all that info, that would be great.

What are the 18 pieces of info that you need?

If you have fully-qualified path-and-filename, then you can obtain a File object using FSO and it will tell you just about anything you need to know about a file.

    DateCreated Property
    DateLastAccessed Property
    DateLastModified Property
    Drive Property
    Name Property
    ParentFolder Property
    Path Property
    ShortName Property
    ShortPath Property
    Size Property
    Type Property

function GetDateCreated( filespec ) {
        var fso, f, s;
        fso = new ActiveXObject( "Scripting.FileSystemObject" );
        f = fso.GetFile( filespec );
        s = f.DateCreated;
        return( s );

So I ask you again:  
If I provide code to create an array of all filespecs in a folder and in the folders below that... (etc), will you be able to accomplish what you need to do?

-- Dan
robotman757Author Commented:
I only need to get the path and file name. The other information is chosen on the other pages by the user. The program sends the list of files to a page that allows the user to select what the security level and need to know category is, and there are a few other choices as well. I have the program also store information about the user and date and time of the transfers. So the main thing I need is a way to get all the files and their paths starting at a certain folder and going through each folder and subfolder. The best option I believe would be to store this info into an array, and then I can send it where I need to.

robotman757Author Commented:
Thanks Dan for your help. I was so close but so far away. I went off on a wild tangent, and forgot about the simple "keep it simple stupid" mentality. I am going to modify the code so that I can get the paths into a hidden list box control. There will be a few more changes to make it all work, but that is not too hard. Thanks again.

Glad to help.  Thanks for the points and the grade :)
-- Dan
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.