<form action="<%= Request.ServerVariables("URL") %>" method="get">
Search For:
<input type="text" name="query"
value="<%= Request.QueryString("query") %>" />
<input type="submit" />
</form>
<br />
<%
' Declare variables
Dim strFileName
Dim strSearchText
Dim objFSO, objTextFile
Dim strReadLineText
Dim intLineNumber
Dim strLineNumbers
' Name of text file to search:
strFileName = "textfilesearch.txt"
' Text to search for:
strSearchText = Request.QueryString("query")
' Display header
Response.Write "Searching Text File "<strong>"
Response.Write strFileName
Response.Write "</strong>" for "<strong>"
Response.Write strSearchText
Response.Write "</strong>":" & vbCrLf
' Create an instance of the the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Open the file
Set objTextFile = objFSO.OpenTextFile(Server.MapPath(strFileName))
' Init line number counter and found line number list
intLineNumber = 0
strLineNumbers = ""
' Loop through text file highlighting found matches and
' making a note of the line numbers where they are found.
' Actually displaying the text file isn't necessary and may
' not be appropriate with larger files, but since this is
' a sample, it gives users something to look at.
Response.Write "<pre>" & vbCrLf
Do While Not objTextFile.AtEndOfStream
intLineNumber = intLineNumber + 1
strReadLineText = objTextFile.ReadLine
If strSearchText <> "" And InStr(strReadLineText, strSearchText) > 0 Then
strReadLineText = Replace(strReadLineText, _
strSearchText, _
"<span style=""background-color:yellow;"">" & strSearchText & "</span>")
strLineNumbers = strLineNumbers & intLineNumber & ", "
End If
Response.Write strReadLineText & vbCrLf
Loop
Response.Write "</pre>" & vbCrLf
' Remove the last separator (", ") from our line number list.
If Len(strLineNumbers) > 2 Then
strLineNumbers = Left(strLineNumbers, Len(strLineNumbers) - 2)
End If
' Close and release file references
objTextFile.Close
Set objTextFile = Nothing
Set objFSO = Nothing
Response.Write "<p>The text searched for was found on the following lines in the file: "
Response.Write strLineNumbers & "</p>"
%>