Read Specific Line of Text File

Joined
Aug 2, 2005
Messages
1
Programming Experience
Beginner
[RESOLVED] Read Specific Line of Text File

Hello, I'm new to the forum and a beginner with VB.net.

I have a simple question for a project I'm working on. I'd like to read a single specific line of the text file. The line of concern is the 2nd to last line of the text file. I'm sure there's a method to do this, but like I said, I'm a novice :)

Thanks,
Brad Davis

Thanks for the help jmcilhinney! Sorry for the post to the incorrect area (I didn't see a VB.net IO formum).
 
Last edited:
Unless your text file is a CSV or TSV then this isn't data access, but rather IO. You would need to open the file using a StreamReader and then read lines until you get to the second last. If you don't know how many lines there are then you should read the whole file, split the contents into lines and get the second last one.
VB.NET:
		'Open file.
		Dim myReader As New IO.StreamReader("file path")

		'Read file.
		Dim fileContents As String = myReader.ReadToEnd()

		'Close file.
		myReader.Close()

		'Seperate lines.
		Dim fileLines As String() = System.Text.RegularExpressions.Regex.Split(fileContents, Environment.NewLine)

		If fileLines.Length > 1 Then
			'Display second last line.
			MessageBox.Show(fileLines(fileLines.Length - 2))
		End If
 
Back
Top