VB - 自上次更改后检索.txt文件的新增内容

时间:2017-09-27 11:26:11

标签: vb.net

所以基本上我要做的就是创建一个日志监视器。我需要监视.txt日志文件的更改,当它发生更改时,检索自上次更改为数组以来的最新行。从那里我将根据线条的内容制作活动。但我无法弄清楚的部分是日志监控。我是VB的新手,本学期刚刚开始我的VB类入门,但我已经用PHP作为业余爱好6年了。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

这是对此C#实现(https://stackoverflow.com/a/2373515/5601657

的vb.net转换

您可以存储上次读取操作的偏移量,并在获得更改的文件通知时将文件搜索到该偏移量。一个例子如下:

主要方法:

<App Background="#eeef">
  <Fuse.iOS.StatusBarConfig ux:Name="statusBarConfig" Style="Dark"/>
    <StackPanel ux:Name="textPanel" Alignment="Center">
      <Text ux:Class="TitleText" Color="#000" TextAlignment="Center" Padding="2"/>
      <TitleText ux:Name="topText">This is a long text aligned horizontally</TitleText>
      <TitleText ux:Name="bottomText">This is a another long text</TitleText>
    </StackPanel>
</App>

从文件方法中读取:

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

写入文件方法:

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