0

From a button click I am trying to read a text file and then output just the last 2 lines into a Label. The data in the text file changes regular but the format is always the same.

This is an example of what is in the text file.

1393
00:23:12,000 --> 00:23:13,000
2020/08/12 12:43:47
+DMR DCC=4
Slot 1 TG=9003 RID=69

The last 2 lines is what I am interested in getting which in the above example would be

+DMR DCC=4
Slot 1 TG=9003 RID=69

This is what I have so far which seems to work but I just feel its a bit messy and was wondering if anyone had any other suggestions.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Label1.text= ReadLog()

End Sub

Public Function ReadLog() As String
    Dim lines() As String = IO.File.ReadAllLines("C:\MyApp\log.txt")
    If lines.Length <= 4 Then Return String.Join(Environment.NewLine, lines)
    Dim lines4(3) As String
    Array.Copy(lines, lines.Length - 3, lines4, 0, 3)
    Return String.Join(Environment.NewLine, lines4)
End Function
Ian Barber
  • 133
  • 8
  • This would probably be better on the Code Review site. (I'd flag it to be moved, but Code Review isn't one of the options.) – Craig Aug 12 '20 at 13:06
  • Here's a similar c# question: https://stackoverflow.com/questions/15867758/read-only-given-last-x-lines-in-txt-file – MatSnow Aug 12 '20 at 13:08

1 Answers1

1

You say that you want the last two lines but the code you have indicates that you want the last four lines. Regardless, set lineCount to the appropriate value in the code below.

Dim lines = File.ReadAllLines(filePath)
Dim lastLines = lines.Skip(Math.Max(0, lines.Length - lineCount))
Dim text = String.Join(Environment.NewLine, lastLines)
jmcilhinney
  • 50,448
  • 5
  • 26
  • 46
  • Thank you. Condensing this down to just 3 lines of code has made it much more readable. Dim lastLines = lines.Skip(Math.Max(0, lines.Length - lineCount)) is something that I would never have figured out. – Ian Barber Aug 12 '20 at 15:02