Author: Gan jiping
You may think: Well, now I know how to write files. But can we do more? Next, let's try to create a search function for the web site.
The key to building a search engine is recursion. Mainly, write a piece of code to search for files under the directory, and then execute the same code for all directories cyclically. Because
To determine the total number of subdirectories, you must execute the search code over and over again until the end of the search. Recursive call is very good!
Create a search page. Assume that an HTML form has been created and 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 above code initializes the variable. The Search function executes the Search function, which is described as follows:
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
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
To open a file, FSO requires the actual file path instead of the web path. For example, c: inetpubwwwroot empindex.html, instead
Www.enfused.com/temp/index.html or/temp/index.html. To convert the latter to the former, use Server. MapPath
("Filename"). filename indicates the web path name.
The above code will be executed in each subdirectory of the folder under the initial directory you specified. Here, the initial directory refers to the web root directory "/". Then
Simply open each file in the directory and check whether it contains the specified string. If the string is found, the link to the file is displayed.
Note: As the number of files and subdirectories increases, the search time will also increase. If you need heavy search work, we recommend that you use other methods.
For example, the Index Server of Microsoft's Index Server.