1

So basically what I'm trying to do is create a log monitor. I need to monitor a .txt log file for changes, and when it changes, retrieve the newest lines since the last change to an array. From there I will make events based on the content of the lines. But the part I cannot figure out is the log monitoring. I'm brand new to VB, just started my Intro to VB class this semester, but I've been programming with PHP as a hobby for 6 years. Any advice?

Zach O.
  • 119
  • 5

1 Answers1

0

This is a vb.net conversion of this C# implementation (https://stackoverflow.com/a/2373515/5601657)

You can store the offset of the last read operation and seek the file to that offset when you get a changed file notification. An example follows:

Main method:

Public Shared Sub Main(args As String())
    File.WriteAllLines("test.txt", New String() {})
    New Thread(Function() ReadFromFile()).Start()
    WriteToFile()
End Sub

Read from file method:

Private Shared Sub ReadFromFile()

    Dim offset As Long = 0
    Dim fsw As New FileSystemWatcher() With { _
    Key .Path = Environment.CurrentDirectory, _
    Key .Filter = "test.txt" _
}

    Dim file__1 As FileStream = File.Open("test.txt", FileMode.Open, FileAccess.Read, FileShare.Write)

    Dim reader As New StreamReader(file__1)
    While True
        fsw.WaitForChanged(WatcherChangeTypes.Changed)

        file__1.Seek(offset, SeekOrigin.Begin)
        If Not reader.EndOfStream Then
            Do
                Console.WriteLine(reader.ReadLine())
            Loop While Not reader.EndOfStream

            offset = file__1.Position
        End If
    End While
End Sub

Write to file method:

Private Shared Sub WriteToFile()
    For i As Integer = 0 To 99
        Dim writeFile As FileStream = File.Open("test.txt", FileMode.Append, FileAccess.Write, FileShare.Read)

        Using file__1 As FileStream = writeFile
            Using sw As New StreamWriter(file__1)
                sw.WriteLine(i)
                Thread.Sleep(100)
            End Using
        End Using
    Next
End Sub
Joseph
  • 380
  • 3
  • 16