Search code examples
vb.netfile.readalllines

How to browse from bottom to top of a text file in vb.net?


I cannot get my code below to work correctly, in fact I want to press a back button in order to go up the lines one by one of a text file then I cut the chain into 3 parts.

Dim LinesOfText() As String = System.IO.File.ReadAllLines("c:\essai.librairie", Encoding.UTF8)
    For line As Integer = LinesOfText.Length - 1 To 0 Step -1

        Dim currentLine As String = LinesOfText(line)

        Dim value As String = currentLine
        Dim startIndex As Integer = 0
        Dim length As Integer = 17

        Dim substring As String = value.Substring(startIndex, length)
        Dim subs As String = value.Substring(17, 90)
        Dim subst As String = value.Substring(107, 120)

        TextBox1.Text = substring
        TextBox2.Text = subs
        TextBox3.Text = subst

    Next

enter image description here


Solution

  • If you store the lines and a line counter so that they are in scope where needed, you can do it like this:

    Imports System.IO
    
    Public Class Form1
    
        Dim lines As String()
        Dim currentLine As Integer = -1
    
        Sub LoadData(filename As String)
            lines = File.ReadAllLines(filename)
            currentLine = lines.Length - 1
    
        End Sub
    
        Sub ShowCurrentLine()
            If currentLine >= 0 Then
                TextBox1.Text = lines(currentLine).Substring(0, 3)
                TextBox2.Text = lines(currentLine).Substring(4, 3)
                TextBox3.Text = lines(currentLine).Substring(8, 3)
                lblLineNo.Text = (currentLine + 1) & "/" & lines.Length
            Else
                TextBox1.Clear()
                TextBox2.Clear()
                TextBox3.Clear()
                lblLineNo.Text = "-"
            End If
    
        End Sub
    
        Private Sub bnNext_Click(sender As Object, e As EventArgs) Handles bnNext.Click
            If currentLine < lines.Length - 1 Then
                currentLine += 1
                ShowCurrentLine()
            End If
    
        End Sub
    
        Private Sub bnPrev_Click(sender As Object, e As EventArgs) Handles bnPrev.Click
            If currentLine > 0 Then
                currentLine -= 1
                ShowCurrentLine()
            End If
    
        End Sub
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            LoadData("C:\temp\SO67209265.txt")
            ShowCurrentLine()
    
        End Sub
    
    End Class
    

    You will need to set the substring parameters for your data—I just used a small text file—and the filename to be loaded.

    The label lblLineNo is used to show the current line number, starting at 1.

    enter image description here