Sort | Array when you use the FileSystemObject object to get a list of files in a directory, do you find that you can't control how they are sorted, such as by name, by extension, by file size, and so on, let's try to sort them out by array.
If you want to sort by name, that would be very simple, but it would be a bit of a hassle if you wanted to sort by file size or file creation time and so on. We will do this through a two-dimensional array.
The following code shows you how to select the order by which to sort, click Sort, and then line up two times.
<HTML>
<HEAD>
<TITLE> File Sorting Demo </TITLE>
</HEAD>
<BODY>
<%
' Set up a demo directory:
CONST DIRECTORY = "/"
' Define sort by constants
CONST file_name = 0 ' sorted by name ... By analogy
CONST File_ext = 1
CONST File_type = 2
CONST file_size = 3
CONST file_created = 4
CONST file_modified = 5
CONST file_accessed = 6
' Get sort commands, default to sort by name
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)
' Set reverse
If sortby = Priorsort Then
Reverse = True
Priorsort =-1
Else
Reverse = False
Priorsort = SortBy
End If
' Next we're going to start with the real code ...
Path = Server.MapPath (DIRECTORY)
Set fso = CreateObject ("Scripting.FileSystemObject")
Set Thecurrentfolder = fso. GetFolder (PATH)
Set curfiles = Thecurrentfolder.files
' Give these files a loop.
Dim Thefiles ()
ReDim thefiles (500) ' I casually set a size
Currentslot =-1 ' Start before-a-slot
' We put all the relevant information of the file into the 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
' Put it in the array.
Thefiles (Currentslot) = Array (fname,fext,ftype,fsize,fcreate,fmod,faccess)
Next
' It's all in the array now, start the next step
FileCount = Currentslot ' Number of files
ReDim Preserve thefiles (currentslot)
' Sort
' (8 = string)
If VarType (thefiles (0) (sortby)) = 8 Then
IF reverse Then kind = 1 Else kind = 2 ' to sort characters
Else
IF reverse Then kind = 3 Else kind = 4 ' number, time ...
End If
For i = FileCount to 0 Step-1
Minmax = thefiles (0) (SortBy)
Minmaxslot = 0
For j = 1 to I
Select Case Kind
Case 1
Mark = (StrComp (Thefiles (j) (SortBy), Minmax, vbTextCompare) < 0)
Case 2
Mark = (StrComp (Thefiles (j) (SortBy), Minmax, vbTextCompare) > 0)
Case 3
Mark = (Thefiles (j) (SortBy) < Minmax)
Case 4
Mark = (Thefiles (j) (SortBy) > Minmax)
End Select
If Mark Then
Minmax = Thefiles (j) (SortBy)
Minmaxslot = J
End If
Next
If Minmaxslot <> i Then
temp = Thefiles (minmaxslot)