Searching with the FSO
August 14, 2000
You may be thinking "Great, so now I know how to write files. I could've
figured that out myself." So you want more tough guy? Let's try building a
search feature for your web site.
The key to building a search engine is recursion. If you don't know
what recursion is, find out
why it's cool.
Basically, you write one piece of code that performs a search on
the files in a directory, and then make that same code loop through
all the subdirectories. Since we don't know ahead of time how many
subdirectories there may be, we have to call this piece of code over
and over again until we're through. Recursion in it's finest.
So let's build the search page. We'll assume that you've already
built an HTML form for a user to input a search string.
Dim objFolder
Dim strSearchText
Dim objFSO
strSearchText = Request.Form("SearchText") <-- The search string
' create the FSO and Folder objects
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(Server.MapPath("/"))
Search objFolder
The above code simple initializes variables and gets us started.
The meat of the search is performed by the Search function,
described below:
Function Search(objFolder)
Dim objSubFolder
'loop through every file in the current folder
For Each objFile in objFolder.Files
Set objTextStream = objFSO.OpenTextFile(objFile.Path,1) <-- For Reading
'read the file's contents into a variable
strFileContents = objTextStream.ReadAll
'if the search string is in the file, then write a link
' to the file
If InStr(1, strFileContents, strSearchText, 1) then
Response.Write "<A HREF=""/" & objFile.Name & _
""">" & objFile.Name & "</A><BR>"
bolFileFound = True
End If
objTextStream.Close
Next
'Here's the recursion part - for each
' subfolder in this directory, run the Search function again
For Each objSubFolder in objFolder.SubFolders
Search objSubFolder
Next
End Function
|
NOTE:
To be able to open files, the FSO requires the actual
path to the file, not the web path. For instance,
c:\inetpub\wwwroot\temp\index.html,
not www.enfused.com/temp/index.html or /temp/index.html. To convert
the latter to the former, we use Server.MapPath("filename"),
where filename represents the web path.
|
The code above will run through every subdirectory of every folder
under the initial folder that you specified, which in this case,
would be the root web path, specified by "/". Then we simply open
each file in the directory, see if the desired string is in that file
and display a link to that file if the search string is found. Not bad, huh?
Note that as the number of files and subdirectories increases,
so will the time it takes to run this search. It's recommended that
if you need a heavy duty search feature, turn to something else,
such as Microsoft's Index Server.
Permissions
The wonders of the File System Object
Content Management with the FSO
|