Read a text file line by line with Visual Basic

Add this code to the very top of the code page:

Read a text file line by line

  • Copy and paste
Imports System.IO
----------------------------------------------------------------------------------
Add the following function:

Public Function ReadALine(ByVal File_Path As String, ByVal TotalLine As Integer, ByVal Line2Read As Integer) As String
Dim Buffer As Array
Dim Line As String
If TotalLine <= Line2Read Then Return "No Such Line" End If Buffer = File.ReadAllLines(File_Path) Line = Buffer(Line2Read) Return Line End Function ----------------------------------------------------------------------------------------- Public Function GetNumberOfLines(ByVal file_path As String) As Integer Dim sr As New StreamReader(file_path) Dim NumberOfLines As Integer Do While sr.Peek >= 0
sr.ReadLine()
NumberOfLines += 1
Loop
Return NumberOfLines

sr.Close()
sr.Dispose()

---------------------------------------------------------------------------------------------

To read a specific line to a textbox

Dim filename As String = "C:\location\file.txt"
TextBox1.Text = (ReadALine(filename, GetNumberOfLines(filename), 1))

'/Replace 1 to line # you would like to read