
FileSystem Object Read Order
Thanks Michael! That was just the trick.
It's pure coincidence that you get ascending order. The order is (more or
less) in order of creation or perhaps addition to the folder.
You can't sort the files collection. You need to build an array of
filenames, sort the array, then use the array to output filenames or use the
array to index back into the Files collection in sorted order if you need
dates/size/etc.. As simple bubble sort is OK for small arrays.
You can index into the Files collection with a simple string -
Files("myfile.ext") or a variable (including an array element reference) -
Files((arSorted(n))). In the second case, you'll get a runtime error unless
you wrap the entire variable reference in ()s as I did in the example below.
Here's a .wsf (WSH 2.0) example:
<job>
<object id='fso' progid='Scripting.FilesystemObject' reference='yes' />
<script language='VBScript'>
'====================================================
'An example of sorting file names with a simple bubble sort.
'====================================================
set oFolder = fso.GetFolder("c:\")
set oFiles = oFolder.Files
Redim arFiles(oFiles.Count -1)
n = -1
'load the array with file names
'
For Each oFile in oFiles
n = n + 1
arFiles(n) = oFile.Name
next
'ascending sort order
'
For n = 0 to ubound(arFiles) -1
For m = n+1 to ubound(arFiles)
if lcase(arFiles(m)) < lcase(arFiles(n)) then
temp = arFiles(m)
arFiles(m) = arFiles(n)
arFiles(n) = temp
end if
Next
Next
msgbox join(arFiles,vbcrlf)
'use the sorted array to index back
'into the Files collection and list path
'
s = ""
for each f in arFiles
'wrapping f in extra ()s is a _must_!
s = s & oFiles((f)).path & vbcrlf
next
msgbox s
'descending sort order
'
For n = 0 to ubound(arFiles) -1
For m = n+1 to ubound(arFiles)
if lcase(arFiles(m)) > lcase(arFiles(n)) then
temp = arFiles(m)
arFiles(m) = arFiles(n)
arFiles(n) = temp
end if
Next
Next
msgbox join(arFiles,vbcrlf)
'use the sorted array to index back
'into the Files collection and list path
'
s = ""
for each f in arFiles
'wrapping f in extra ()s is a _must_!
s = s & oFiles((f)).path & vbcrlf
next
msgbox s
</script>
</job>
-
Michael Harris
When I use the MS example script for reading every file in a directory, I
notice that the order that the files in the files collection are returned
are in ascending order according to filename.
' Create FileSytemObject Component
Set ScriptObject = CreateObject("Scripting.FileSystemObject")
Set f = ScriptObject.GetFolder("c:\Inetpub\wwwroot\")
Set fc = f.Files
For Each f1 in fc
s = f + "\" + f1.name
Set MyFile = ScriptObject.OpenTextFile(s, ForReading)
Response.Write MyFile.ReadAll
Next
Does anyone know of a way to sort files in a files collection in
descending
order according to filename?
Thanks,
--
Patrick Burgess