Knowing how to read a text file is almost a requirement in the programming world. Microsoft Visual Basic is a programming language that can be used to develop programs and manipulate data in files. It’s useful to know how to read a text file line-by-line when you need to transfer the data to another file or display it in your program. In a few steps, you can write Visual Basic code to read all the lines in a text file.
- Skill level:
Other People Are Reading
Start Microsoft Visual Basic 2010 Express and click the “File” menu then select “New Project…”. Click “Windows Forms Application” and select “OK.”
Open Notepad and type the following:
this is line 1 this is line 2 this is line 3 this is line 4 this is line 5
Save the file to “C:\” as “readLines.txt.”
Click “Toolbox” and double-click “Button” to add a new button to “Form 1.” Double-click “Button 1” to open the “Form1.vb” module.
Type “Imports System.IO” in the very first line of “Form1.vb.” Type the following to declare your variables inside “Private Sub Button1_Click”:
Dim text File As File Dim file Reader As System.IO.StreamReader Dim line Read As String
Type the following to open the “readLines.txt” file:
file Reader = textFile.OpenText("C:\readLines.txt")
Type the following to loop through all the lines in “readLines.txt” and display the results in a message box:
While fileReader.Peek <> -1 line Read = fileReader.ReadLine() MsgBox(lineRead) End While
Type the following to close the file:
Press “F5” to run your program and click “Button 1” to execute your code.
- 20 of the funniest online reviews ever
- 14 Biggest lies people tell in online dating sites
- Hilarious things Google thinks you're trying to search for