Read a text file line by line - Visual Basic .NET

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

Add this code to the very top of the code page:
First import:
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
Then add one more 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
            NumberOfLines += 1
        Return NumberOfLines
    End Function

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.

Share This

Home | About | Contact | Privacy Policy

Copyright 2017 - All Rights Reserved.