Public Class FileTextSearcher
Private _Matches As New ArrayList
Private _FileFilter As String
Private _SearchText As String
Private _CaseSensitive As Boolean = True
Public ReadOnly Property Matches() As ArrayList
Get
Return _Matches
End Get
End Property
Public Property FileFilter() As String
Get
Return _FileFilter
End Get
Set(ByVal Value As String)
_FileFilter = Value
End Set
End Property
Public Property SearchText() As String
Get
Return _SearchText
End Get
Set(ByVal Value As String)
_SearchText = Value
End Set
End Property
Public Property CaseSensitive() As Boolean
Get
Return _CaseSensitive
End Get
Set(ByVal Value As Boolean)
_CaseSensitive = Value
End Set
End Property
Public Sub New(ByVal fileFilter As String, _
ByVal searchText As String)
Me.FileFilter = fileFilter
Me.SearchText = searchText
End Sub
Public Sub Search(ByVal startingPath As String)
Matches.Clear()
SearchDirectory(New DirectoryInfo(startingPath))
End Sub
Private Sub SearchDirectory(ByVal dir As DirectoryInfo)
' Lấy các file trong thư mục này.
Dim FileItem As FileInfo
For Each FileItem In dir.GetFiles(FileFilter)
' Kiểm tra file này có trùng khớp hay không.
If TestFileForMatch(FileItem) Then
Matches.Add(FileItem)
End If
Next
' Bạn có thể thêm logic đệ quy ở đây bằng cách gọi
' SearchDirectory trên tất cả các thư mục con (xem mục 5.7).
End Sub
Private Function TestFileForMatch(ByVal file As FileInfo) As Boolean
' Mở file.
Dim fs As FileStream = file.OpenRead()
Dim Match As Boolean = False
Dim MatchCount, MatchPosition As Integer
Dim Character, MatchCharacter As String
' Đọc qua toàn bộ file.
Do Until fs.Position = fs.Length
' Lấy một ký tự từ file.
Character = Convert.ToChar(fs.ReadByte())
' Lấy ký tự kế tiếp từ chuỗi cần tìm để đem so trùng.
MatchCharacter = SearchText.Substring(MatchPosition, 1)
If String.Compare(Character, MatchCharacter, _
Not Me.CaseSensitive) = 0 Then
' Chúng trùng khớp. Bây giờ thử so trùng ký tự kế tiếp.
MatchPosition += 1
Else
' Chúng không trùng khớp. Làm lại từ đầu.
MatchPosition = 0
End If
' Kiểm tra toàn bộ chuỗi đã được so trùng hay chưa.
If MatchPosition = SearchText.Length - 1 Then
Return True
End If
Loop
fs.Close()
Return False
End Function
End Class
Bookmarks