Sort a folder list retreived from FileSystemObject in reverse file date order.

Here is a snip of my current code.  Currently, the folder list is sorted alphabetacly.
I want objFolderContents to be sorted in reverse file date order(newest folder at the top)

Set objFSO = CreateObject("Scripting.FileSystemObject")
strPathInfo = baseDir & "\users\" & gp
Set objFolder = objFSO.GetFolder(strPathInfo)
Set objFolderContents = objFolder.SubFolders
'Run a loop through the directory list
For each FolderItem In objFolderContents

I have found several examples of sorting in ASP but I'm having a lot of trouble getting them to work.  Is it because I am using a "set object"?

Or maybe is it possible to ask FileSystemObject for the list sorted the way I want?

I need an example that will work with my code.

Who is Participating?
anthonywjones66Connect With a Mentor Commented:

For each FolderItem In objFolderContents


Dim i
Dim aoFolders

i = objFolder.SubFolders.count -1
ReDim aoFolders(i)

For each FolderItem in objFolder.SubFolders
      Set aoFolders(i) = FolderItem
      i = i - 1

For Each FolderItem In aoFolders
'The rest of you code here.

aoFolders is array of folder objects held in reverse order.


GarveConnect With a Mentor Commented:
The short answer is that you can't sort the files using the FSO - damn shame!

The following links give examples of placing the files in an array and then sorting that.

You can also use javascript to sort them, which would allow the user to choose whether they are sorted by date, size or alphabetically.

Finally of course, if you only have a few files which never change, you could name them 01file.txt, 02file.txt etc in the order you want.

AlfaNoMoreConnect With a Mentor Commented:
For total flexibility, you should place them inside a Recordset object, and then use the .sort method that is part of that object:

Dim objFilesRS

Set objFilesRS = Server.CreateObject("ADODB.Recordset")

objFilesRS.Fields.Append "FileName", adVarchar, 255
objFilesRS.Fields.Append "dateCreated" adDate

For Each file in objFSO

    objFilesRS.Fields("FileName").Value = file.Name
    objFilesRS.Fields("dateCreated").Value = file.dateCreated

objFilesRS.Sort = "dateCreated DESC"

This is just a quick example, the following is much more thorough:
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.