Public Class Words
' Object to store the current state, for passing to the caller.
Public Class CurrentState
Public LinesCounted As Integer
Public WordsMatched As Integer
End Class
Public SourceFile As String
Public CompareString As String
Private WordCount As Integer = 0
Private LinesCounted As Integer = 0
Public Sub CountWords( _
ByVal worker As System.ComponentModel.BackgroundWorker, _
ByVal e As System.ComponentModel.DoWorkEventArgs _
)
' Initialize the variables.
Dim state As New CurrentState
Dim myStream As System.IO.StreamReader = Nothing
Dim line = ""
Dim elapsedTime = 20
Dim lastReportDateTime = Now
If CompareString Is Nothing Or _
CompareString = System.String.Empty Then
Throw New Exception("CompareString not specified.")
End If
Try
' Open a new stream.
myStream = My.Computer.FileSystem.OpenTextFileReader(SourceFile)
' Do while there are lines remaining in the file to be read.
Do While Not myStream.EndOfStream
If worker.CancellationPending Then
e.Cancel = True
Exit Do
Else
line = myStream.ReadLine
WordCount += CountInString(line, CompareString)
LinesCounted += 1
' Raise an event so the form can monitor progress.
If Now > lastReportDateTime.AddMilliseconds(elapsedTime) Then
state.LinesCounted = LinesCounted
state.WordsMatched = WordCount
worker.ReportProgress(0, state)
lastReportDateTime = Now.AddMilliseconds(elapsedTime)
End If
End If
Loop
' Report the final count values.
state.LinesCounted = LinesCounted
state.WordsMatched = WordCount
worker.ReportProgress(0, state)
Finally
If myStream IsNot Nothing Then
' Close the file.
myStream.Close()
End If
End Try
End Sub
Private Function CountInString( _
ByVal SourceString As String, _
ByVal CompareString As String _
) As Integer
' This function counts the number of times
' a word is found in a line.
If SourceString Is Nothing Then
Return 0
End If
Dim regex As New System.Text.RegularExpressions.Regex( _
System.Text.RegularExpressions.Regex.Escape(CompareString))
Dim matches As System.Text.RegularExpressions.MatchCollection
matches = regex.Matches(SourceString)
Return matches.Count
End Function
End Class