ASP 101 - Active Server Pages 101 textfilesearch.aspx
<%@ Page Language="VB" EnableViewState="False" %>
<%@ Import Namespace="System.IO" %>
<script runat="server">
	Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs)
		Const strFileName As String = "textfilesearch.txt"
		Dim strSearchText As String
		Dim myStreamReader  As StreamReader
		Dim myStringBuilder As StringBuilder
		Dim strLineText     As String
		Dim intLineNumber  As Integer
		Dim strLineNumbers As String
		' Get text to search for:
		strSearchText = txtQuery.Text
		' Set labels that we currently know:
		litFileName.Text = strFileName
		litQuery.Text    = strSearchText
		' Initialize our line number variables:
		intLineNumber  = 0
		strLineNumbers = ""
		' Get a StreamReader to the file to be searched and create
		' a StringBuilder to hold it's modified text to be displayed
		' later.
		myStreamReader  = File.OpenText(Server.MapPath(strFileName))
		myStringBuilder = New StringBuilder()
		' Loop through file looking for search matches and
		' highlighting them in the results.  If we find a match
		' we also make note of the line number.
		'Do While Not myStreamReader.EndOfStream ' .NET 2.0 Syntax
		Do While myStreamReader.Peek() >= 0 ' .NET 1.x Syntax
			intLineNumber = intLineNumber + 1
			strLineText   = myStreamReader.ReadLine()
			If strSearchText <> "" And InStr(strLineText, strSearchText) > 0 Then
				strLineText = Replace(strLineText, strSearchText, _
					"<span style=""background-color:yellow;"">" & strSearchText & "</span>")
				strLineNumbers = strLineNumbers & intLineNumber & ", "
			End If
			'myStringBuilder.AppendLine(strLineText) ' .NET 2.0 Syntax
			myStringBuilder.Append(strLineText & vbCrLf) ' .NET 1.x Syntax
		' Display the file with the matches highlighted:
		litHighlightedResults.Text = myStringBuilder.ToString()
		myStringBuilder = Nothing
		' Remove the last separator (", ") from our line number list
		' and then print out the list.
		If Len(strLineNumbers) > 2 Then
			strLineNumbers = Left(strLineNumbers, Len(strLineNumbers) - 2)
		End If
		litLineNumbers.Text = strLineNumbers
	End Sub
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="" >
    <title>ASP.NET Text File Search Sample</title>
    <form id="frmSearch" runat="server"
		Search For: <asp:TextBox id="txtQuery" runat="server" />
		<asp:Button id="btnSearch" runat="server"
	Searching Text File
	"<strong><asp:literal id="litFileName" runat="server" /></strong>"
	"<strong><asp:literal id="litQuery" runat="server" /></strong>":
<asp:literal id="litHighlightedResults" runat="server" />
	The text searched for was found on the following lines in the file:
	<asp:literal id="litLineNumbers" runat="server" />
<hr />
Click <a href="">here</a>
to read about and download the source code.