簡體   English   中英

如何檢查某個字符串的文本文件並在添加該字符串時通知?

[英]How do I check a text file for a certain string and notify when that string has been added?

我想要做的是監控我玩的游戲的聊天記錄。 我想制作一個程序,它會在聊天中提到我的角色名稱時通知我。 如果聊天中提到我的名字,它會告訴我。 然后它一遍又一遍地掃描文件后再次告訴我。 每次文件更改。 我只想在每次提到我的名字時收到一次通知。 有人可以幫我更正此代碼以執行我需要的操作嗎?

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 次,每次提到它時也只告訴我一次。 我只想在每次提到它時告訴我。 然后等待下一個。 也許通過在提到我的名字時檢查行號,如果數字大於上次提到的數字,然后告訴我如果不是然后跳過它?

我不知道該怎么做。

您可以記錄角色名稱出現的次數,並在發生變化時收到通知。 此外,如果您從經常更改的文件中讀取數據,您可能會收到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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM