When you think ASP, think...
Recent Articles xml
All Articles
ASP.NET Articles
Related Web Technologies
User Tips!
Coding Tips
spgif spgif

Sample Chapters
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Stump the SQL Guru!
XML Info
Author an Article
spgif spgif
ASP ASP.NET ASP FAQs Feedback topnav-right

The 4 Guys Present: ASPFAQs.com

Jump to a FAQ
Enter FAQ #:
..or see our 10 Most Viewed FAQs.

4GuysFromRolla.com : ASP FAQS : FileSystemObject


When I get a list of all files in a directory via the FileSystemObject, they aren't ordered in any reasonable way. How can I sort the files by name? Or by size? Or by date created? Or...

[Print this FAQ]

Answer: The short answer is: Copy all the files into an array and then sort the array.

If all you want to do is sort the files by name, then that is pretty easy to do.

However, if you want to sort the files by size or date created or whatever, then you can't use a simple array. You must use a two-dimensional array, an array of VBScript objects (that is, instances of a VBScript Class that you define), or--my own preference for this particular task--an array of arrays.

The following code is a demonstration page that allows the user to choose the desired sort by clicking in a link at the head of any column. (And clicking the same link twice will reverse the sort!) You might be able to use some variation on this almost unchanged for your own purposes.

However, if you want to "fix" the sort order, it's easy to do. Just get rid of the HTML links (the <A HREF=...> stuff) and the JavaScript code and hard-code in the values for sortBy and priorSort and presto! You will have your sorted directory listing.

Give it a try!

<TITLE>Bill Wilkinson's sort-it-any-which-way Directory Listing</TITLE>


' In this demo, at least, we don't allow user to change directories...
' Change the DIRECTORY to point to any virtual directory of your choice.
CONST DIRECTORY = "/" ' relative path in virtual directories

' Specify one of these constants for "sortBy"...

' get requested sort order, if not first time here...
' (forward by name is default)
req = Request("sortBy")
If Len(req) < 1 Then sortBy = 0 Else sortBy = CInt(req)
req = Request("priorSort")
If Len(req) < 1 Then priorSort = -1 Else priorSort = CInt(req)

' did user ask for same sort? to reverse the order?
' but if so, then zap priorSort so clicking again will do forward!
If sortBy = priorSort Then
    reverse = true
    priorSort = -1
    reverse = false
    priorSort = sortBy
End If

' now start the *real* code...
path = Server.MapPath( DIRECTORY )

Set fso = CreateObject("Scripting.FileSystemObject")
Set theCurrentFolder = fso.GetFolder( path )
Set curFiles = theCurrentFolder.Files
' And now a loop for the files
Dim theFiles( )
ReDim theFiles( 500 ) ' arbitrary size!
currentSlot = -1 ' start before first slot

' We collect all the info about each file and put it into one
' "slot" in our "theFiles" array.
For Each fileItem in curFiles
    fname = fileItem.Name
    fext = InStrRev( fname, "." )
    If fext < 1 Then fext = "" Else fext = Mid(fname,fext+1)
    ftype = fileItem.Type
    fsize = fileItem.Size
    fcreate = fileItem.DateCreated
    fmod = fileItem.DateLastModified
    faccess = fileItem.DateLastAccessed
    currentSlot = currentSlot + 1
    If currentSlot > UBound( theFiles ) Then
        ReDim Preserve theFiles( currentSlot + 99 )
    End If
    ' note that what we put here is an array!
    theFiles(currentSlot) = Array(fname,fext,ftype,fsize,fcreate,fmod,faccess)
' files are now in the array...
' As noted, it is actually an ARRAY *OF* ARRAYS. Which makes
' picking the column we will sort on easier!
' ...size and sort it...
fileCount = currentSlot ' actually, count is 1 more, since we start at 0
ReDim Preserve theFiles( currentSlot ) ' really not necessary...just neater!

' First, determine which "kind" of sort we are doing.
' (VarType=8 means "string")
If VarType( theFiles( 0 )( sortBy ) ) = 8 Then
    If reverse Then kind = 1 Else kind = 2 ' sorting strings...
    If reverse Then kind = 3 Else kind = 4 ' non-strings (numbers, dates)
End If

' A simple bubble sort for now...easier to follow the code...
For i = fileCount TO 0 Step -1
    minmax = theFiles( 0 )( sortBy )
    minmaxSlot = 0
    For j = 1 To i
        Select Case kind ' which kind of sort are we doing?
        ' after the "is bigger/smaller" test (as appropriate),
        ' mark will be true if we need to "remember" this slot...
        Case 1 ' string, reverse...we do case INsensitive!
            mark = (strComp( theFiles(j)(sortBy), minmax, vbTextCompare ) < 0)
        Case 2 ' string, forward...we do case INsensitive!
            mark = (strComp( theFiles(j)(sortBy), minmax, vbTextCompare ) > 0)
        Case 3 ' non-string, reverse ...
            mark = (theFiles( j )( sortBy ) < minmax)
        Case 4 ' non-string, forward ...
            mark = (theFiles( j )( sortBy ) > minmax)
        End Select
        ' so is the current slot bigger/smaller than the remembered one?
        If mark Then
            ' yep, so remember this one instead!
            minmax = theFiles( j )( sortBy )
            minmaxSlot = j
        End If
    ' is the last slot the min (or max), as it should be?
    If minmaxSlot <> i Then
        ' nope...so do the needed swap...
        temp = theFiles( minmaxSlot )
        theFiles( minmaxSlot ) = theFiles( i )
        theFiles( i ) = temp
    End If
' Ta-da! The array is sorted!
<FORM Name="doSort" Method="Get">
<INPUT Type=Hidden Name=priorSort Value="<% = priorSort %>">
<INPUT Type=Hidden Name=sortBy Value="-1">

<SCRIPT Language="JavaScript">
function reSort( which )
    document.doSort.sortBy.value = which;
    document.doSort.submit( );

<FONT Size="+2">
Showing <% = (fileCount+1) %> files from directory <% = path %>
Click on a column heading to sort by that column. Click the same column
again to reverse the sort.

<TABLE Border=1 CellPadding=3>
    <TH><A HREF="javascript:reSort(0);">File name</A></TH>
    <TH><A HREF="javascript:reSort(1);">Extension</A></TH>
    <TH><A HREF="javascript:reSort(2);">Type</A></TH>
    <TH><A HREF="javascript:reSort(3);">Size</A></TH>
    <TH><A HREF="javascript:reSort(4);">Created</A></TH>
    <TH><A HREF="javascript:reSort(5);">Last modified</A></TH>
    <TH><A HREF="javascript:reSort(6);">Last accessed</A></TH>
' With the array nicely sorted, this part is a piece of cake!
For i = 0 To fileCount
    Response.Write "<TR>" & vbNewLine
    For j = 0 To UBound( theFiles(i) )
        Response.Write "    <TD>" & theFiles(i)(j) & "</TD>" & vbNewLine
    Response.Write "</TR>" & vbNewLine


For more information check out these articles:
Sorting a One-Dimensional Array Using Bubble Sort
FileSystemObject FAQs

Bill Wilkinson

FAQ posted by Bill Wilkinson at 1/22/2001 5:10:02 PM to the FileSystemObject category. This FAQ has been viewed 168,750 times.

Do you have a FAQ you'd like to suggest? Suggestions? Comments? If so, send it in! Also, if you'd like to be a FAQ Admin (creating/editing FAQs), let me know! If you are looking for other FAQs, be sure to check out the 4Guys FAQ and Commonly Asked Messageboard Questions!

Most Viewed FAQs:

1.) How can I format numbers and date/times using ASP.NET? For example, I want to format a number as a currency. (761643 views)
2.) I am using Access and getting a 80004005 error (or a [Microsoft][ODBC Microsoft Access Driver] The Microsoft Jet database engine cannot open the file '(unknown)' error) when trying to open a connection! How can I fix this problem? (207777 views)
3.) How can I convert a Recordset into an array? Also, how can I convert an array into a Recordset? (202549 views)
4.) How can I quickly sort a VBScript array? (196039 views)
5.) How can I find out if a record already exists in a database? If it doesn't, I want to add it. (156019 views)
6.) How do I display data on a web page using arrays instead of Do...While...MoveNext...???... (152331 views)
7.) When I get a list of all files in a directory via the FileSystemObject, they aren't ordered in any reasonable way. How can I sort the files by name? Or by size? Or by date created? Or... (140381 views)
8.) For session variables to work, must the Web visitor have cookies enabled? (110162 views)
9.) Can I send emails without using CDONTS? (107083 views)
10.) How can I take the result of a SELECT...MULTIPLE or a group of same-named checkboxes and turn it into a query? That is, if the user selects 3 answers, how can I construct a query that looks for all 3? (106308 views)
Last computed at 9/17/2007 3:22:00 AM

ASP.NET [1.x] [2.0] | ASPFAQs.com | Advertise | Feedback | Author an Article