如何检查某个字符串的文本文件,并在添加该字符串时通知?

时间:2016-04-07 06:11:20

标签: vb.net

我要做的是监控我玩的游戏的聊天记录。我想创建一个程序,只要聊天中提到我的角色名称,就会通知我。如果在聊天中提到我的名字它会告诉我。然后它一遍又一遍地再次扫描文件后再次告诉我。每次文件更改。我只希望在提到我的名字的每个实例时收到通知。有人可以帮我纠正这段代码来做我需要的吗?

Private Sub FileSystemWatcher1_Changed(sender As Object, e As IO.FileSystemEventArgs) Handles FileSystemWatcher1.Changed
    If e.FullPath = "C:\Games\Chat\Logs\chat.txt" Then
        Dim fileContents As String = My.Computer.FileSystem.ReadAllText(e.FullPath)

        ' Convert the text to lower case to provide for better trigger matching if case sensitivity
        ' isn't an issue.
        If fileContents.ToLower.Contains("palumbo") Then
            Dim strMessage As String
            strMessage = "Name Mentioned In Chat!" & vbNewLine
            txtMessage.SelectionColor = Color.Red
            txtMessage.SelectionFont = New Font("Arial", 18, FontStyle.Bold)
            txtMessage.AppendText(strMessage)
        End If
    End If

End Sub

这样做的方法是检查文件是否看到它被提及然后它告诉我。然后,如果文件更改了添加到文件的任何内容,它会再次扫描并再次告诉我。即使我的名字没有被再次提及。我不确定我需要添加什么代码只告诉我每次提到它,即使我的名字被提到100次。我只希望每次提到它时告诉我。然后等待下一个。也许通过在提到我的名字时检查行号,如果数字大于上次提到的那个,那么告诉我,如果没有,那么跳过它?

我不知道怎么做。

1 个答案:

答案 0 :(得分:1)

您可以保留字符名称出现次数的计数,并在更改时收到通知。此外,如果您从经常更改的文件中读取内容,那么您可能会获得IOException,因此可以通过一种方式复制并阅读该文件。

Private Sub FileSystemWatcher1_Changed(sender As Object, e As IO.FileSystemEventArgs) Handles FileSystemWatcher1.Changed
    If e.FullPath = "C:\Games\Chat\Logs\chat.txt" Then
        'temp file in different dir from the one being monitored
        Dim tmpfile As String = "C:\chat.txt"

        FileCopy(e.FullPath, tmpfile)

        Dim fileContents As String = My.Computer.FileSystem.ReadAllText(tmpfile)

        Static chatNameOccurences As Integer = 0
        Dim chatName As String = "palumbo"

        ' Convert the text to lower case to provide for better trigger matching if case sensitivity
        ' isn't an issue.
        If fileContents.ToLower.Contains(chatName) Then
            Dim occurrences As Integer = CountMatches(fileContents.ToLower, chatName)
            If Not occurrences.Equals(chatNameOccurences) Then
                chatNameOccurences = occurrences
                Dim strMessage As String
                strMessage = "Name Mentioned In Chat " & chatNameOccurences & " times!" & vbNewLine
                txtMessage.SelectionColor = Color.Red
                txtMessage.SelectionFont = New Font("Arial", 18, FontStyle.Bold)
                txtMessage.AppendText(strMessage)
            End If
        End If
    End If

End Sub

Public Function CountMatches(ByVal value As String, ByVal ch As String) As Integer
    Return New System.Text.RegularExpressions.Regex(ch).Matches(value).Count
End Function