//  home   //  advanced search   //  news   //  categories   //  sql build chart   //  downloads   //  statistics
 ASP FAQ 
Home
ASP FAQ Tutorials

   8000XXXX Errors
   Alerts
   ASP.NET 2.0
   Classic ASP 1.0
      COM / ActiveX Components
      Forms
      General Topics
      Date/Time Routines
      Email Scripts & Info
      Files/Directories & FSO
   Databases
   General Concepts
   Search Engine Optimization (SEO)

Contact Us
Site Map

Search

Web
aspfaq.com
tutorials.aspfaq.com
classicasp.aspfaq.com

ASP FAQ Tutorials :: Classic ASP 1.0 :: Files/Directories & FSO :: How do I sort a list of files?


How do I sort a list of files?

One of IIS' great built-in tools is FileSystemObject. Unfortunately, there is no native way to produce a file listing in the order you specify. For example, consider the following code snippet: 
 
<% 
    folder = "C:\" 
 
    set fso = CreateObject("Scripting.fileSystemObject") 
    set fold = fso.getFolder(folder) 
    for each file in fold.files 
        response.write file.name & "<br>" 
    next 
    set fold = nothing: set fso = nothing 
%>
 
This produces a list of files in seemingly random order. It is not ordered by name, file size, type, date modified, date accessed, archive, read-only, system, hidden, super hidden... 
 
Here are three ways you can order your files alphabetically; the first uses a VBScript sort routine, the second uses a JScript sort routine, and the third uses a database. 
 
Here is the VBScript version (thanks for the help with this, Luke Magnus): 
 
<% 
    folder = "C:\" 
 
    set fso = CreateObject("Scripting.fileSystemObject") 
    set fold = fso.getFolder(folder) 
    fileCount = fold.files.count 
    dim fNames() 
    redim fNames(fileCount) 
    cFcount = 0 
    for each file in fold.files 
        cFcount = cFcount + 1 
        fNames(cFcount) = lcase(file.name) 
    next 
    for tName = 1 to fileCount 
        for nName = (tName + 1) to fileCount 
            if strComp(fNames(tName),fNames(nName),0)=1 then 
                buffer = fNames(nName) 
                fNames(nName) = fNames(tName) 
                fNames(tName) = buffer 
            end if 
        next 
    next 
    for i = 1 to fileCount 
        content = content & fNames(i) & "<br>" 
    next 
    Response.Write content 
%>
 
Here is the JScript sort version: 
 
<script language='jscript' runat='server'> 
    // remember to double-up backslashes: 
    var folder = 'C:\\'; 
 
    var fso = new ActiveXObject('Scripting.FileSystemObject'); 
    var fold = fso.GetFolder(folder); filesArrayString = ''; 
    for (files = new Enumerator(fold.files); !files.atEnd(); files.moveNext()) 
    { 
        var thisFile = files.item(); 
        thisFile=thisFile.name.toLowerCase(); 
        filesArrayString+=thisFile+'/'; 
    } 
    var lenString = filesArrayString.length-1; 
    filesArrayString = filesArrayString.substring(0,lenString); 
    var filesArraySplit = filesArrayString.split('/'); filesArraySplit.sort(); 
    Response.Write(filesArraySplit.join('<br>')); 
</script>
 
And here is the database version (you'll want to create a simple table, called fileTable, with a filename column, varchar(255)): 
 
<% 
    set conn = CreateObject("ADODB.Connection") 
    conn.open "<connection string>" 
    set fso = CreateObject("Scripting.FileSystemObject") 
    set fold = fso.getFolder("c:\") 
    for each file in fold.files 
        sql = sql & "INSERT INTO fileTable(filename)" 
        sql = sql & " VALUES('" & file.name & "'); " 
    next 
    conn.execute(sql) 
    sql = "SELECT filename FROM fileTable ORDER BY filename" 
    set rs = conn.execute(sql) 
    do while not rs.eof 
        filename = rs("filename") 
        if left(filename,5) = "D0101" then 
            fileURL = server.urlEncode(filename) 
            response.write("<a href='Documents/" & fileURL 
            response.write("'>" & filename & "</a><br>") 
        end if 
        rs.movenext 
    loop 
    rs.close: set rs = nothing 
    conn.execute("DELETE FROM fileTable") 
    conn.close: set conn = nothing 
%>
 
The bonus with the database version is that you can insert other elements (such as extension or DateLastModified), and order in different ways (file type; creation date, ascending or descending; reverse alphabetical; etc...). A slightly more efficient way to generate a list of files ordered in whatever way you like would be to use a recordset opened as adOpenDynamic: 
 
<% 
    CONST adFldIsNullable = &H00000020 
    CONST adVarChar = 200 
    CONST adDate = 7 
    CONST adOpenDynamic = 2 
    CONST adUseClient = 3 
 
    response.write "<table border=1 cellpadding=5 cellspacing=0" & _ 
        " bordercolor=#CCCCCC style='font:8pt tahoma'>" 
 
    set fso = CreateObject("scripting.filesystemobject") 
    set folder = fso.getFolder("C:\") 
 
if folder.files.count > 0 then 
    Set rs = CreateObject("ADODB.Recordset") 
 
    With rs 
        .CursorLocation = adUseClient 
        .CursorType = adOpenDynamic 
        .Fields.Append "filename", adVarChar, 255, adFldIsNullable 
        .Fields.Append "filemod", adDate, 32, adFldIsNullable 
        .open 
 
        for each file in folder.Files 
            .AddNew 
            .Fields("filename") = file.Name 
            .Fields("filemod") = file.dateLastModified 
            .update 
        next 
 
        ' list oldest first 
 
        .Sort = "filemod ASC" 
        .MoveFirst 
        response.write "<tr><th colspan=2 bgcolor=#CCCCCC>" & _ 
            .sort & "</th></tr>" & _ 
            "<tr bgcolor=#EFEFEF><th>Name</th>" & _ 
            "<th>Modified</th></tr>" 
        do while not .eof 
            Response.Write "<tr><td>" & .Fields(0) & "</td>" & _ 
            "<td>" & .Fields(1) & "</td></tr>" 
            .Movenext 
        loop 
     
        ' list newest first 
     
        .Sort = "filemod DESC" 
        .MoveFirst 
        response.write "<tr><th colspan=2 bgcolor=#CCCCCC>" & _ 
            .sort & "</th></tr>" & _ 
            "<tr bgcolor=#EFEFEF><th>Name</th>" & _ 
            "<th>Modified</th></tr>" 
        do while not .eof 
            Response.Write "<tr><td>" & .Fields(0) & "</td>" & _ 
            "<td>" & .Fields(1) & "</td></tr>" 
            .Movenext 
        loop 
 
        ' list alphabetically 
     
        .Sort = "filename ASC" 
        .MoveFirst 
        response.write "<tr><th colspan=2 bgcolor=#CCCCCC>" & _ 
            .sort & "</th></tr>" & _ 
            "<tr bgcolor=#EFEFEF><th>Name</th>" & _ 
            "<th>Modified</th></tr>" 
        do while not .eof 
            Response.Write "<tr><td>" & .Fields(0) & "</td>" & _ 
            "<td>" & .Fields(1) & "</td></tr>" 
            .Movenext 
        loop 
 
        .close 
    end with 
    response.write "</table>" 
    set rs = nothing 
end if 
set folder = nothing 
set fso = nothing 
%>

Related Articles

Can I include a file in both server-side and client-side script?
Can I read / write a user's file without a prompt?
Can I rename a file using FileSystemObject?
Could I get some help working with files using FileSystemObject?
How do I avoid 'the red x' when an image is missing?
How do I change the modified time of a file?
How do I create / manipulate images from ASP?
How do I dynamically include files?
How do I find the owner, author, and other properties of a file?
How do I get a list of a folder's subfolders?
How do I get the name of the current URL / page?
How do I prevent people from 'leeching' my CSS or JS files?
How do I prevent people from 'leeching' my images?
How do I retrieve a random file from a given folder?
How do I send the correct filename with BinaryWrite?
How do I use FileSystemObject to create a file on the client?
Why do I get 'Disk not ready' errors with FileSystemObject?
Why do I get 'Invalid procedure call or argument'?
Why do I get 'Path not found' errors with Scripting.FileSystemObject?
Why do I get 'Permission Denied' errors with FileSystemObject?
Why do I get 800A0034 errors?
Why do I get 800A003E / Input past end of file errors?
Why do I get 800A0BBA errors?
Why do I get 800A0BBC errors?
Why do I get an 'Invalid Path Character' error?
Why do I get permissions errors after upgrading to Windows XP?
Why does FileSystemObject hang all of a sudden?
Why is 'the operation completed successfully' an error message?

 

 


Created: 7/16/2000 | Last Updated: 7/23/2004 | broken links | helpful | not helpful | statistics
© Copyright 2006, UBR, Inc. All Rights Reserved. (301)

 

Copyright 1999-2006, All rights reserved.
Finding content
Finding content.  An error has occured...