FSO Author: Gan Ganping
You might think: OK, now I know how to write a file. But can you do more? Here's a try to create a search function for your Web site.
The key to building a search engine is recursion. Basically, write a section of code to search the files in the directory, and then execute the same code for all the directory loops. Because
To determine how many subdirectories there are in total, you must execute the search code over and over until the end. Recursive call very good!
Below to create a search page. Suppose you've created an HTML form in which the user enters 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 code above simply initializes the variable, and the search function performs the searching function, as described below:
Function Search (objfolder)
Dim Objsubfolder
' Loop through every file in '
Folder
For each objfile in Objfolder.files
Set objTextStream = objFSO.OpenTextFile (objfile.path,1) <-for Reading
' Read the file ' contents into a
Variable
Strfilecontents = Objtextstream.readall
' If ' 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
In order to open the file, the FSO requires the actual file path, not the Web path. For example, it's c:inetpubwwwroot empindex.html, not
Www.enfused.com/temp/index.html or/temp/index.html. In order to convert the latter to the former, use the Server.MapPath
("filename"), filename represents the Web path name.
The code above will be executed in each subdirectory of the folder you specify in the initial directory, where the initial directory refers to the Web root directory "/". And then
Simply open each file in the directory to see if it contains the specified string, and if the string is found, the link to that file is displayed.
Note that as the number of files and subdirectories increases, the amount of time spent searching will increase. If you need heavy search work, suggest you take the other side
, such as the Index Server of Microsoft Inc.