Visual Basic 2010 (Console) Guide
Reading Text Files

A basic definition of a text file is that it is a sequence of printable characters organised on a line-by-line basis. The end of each line usually has a termination marker such as a semi-colon or a carriage return.

The following program reads from a small text file, get the file by clicking here with the right mouse button and saving it. There are 6 lines in the file, a question, 4 possible answers and the correct answer.

You will need to add the following statement to the using section at the top of the code window,

Imports System.IO

Read All Text

This is the easiest way to get the entire contents of a text file. Unfortunately, you are unlikely to need to use this method.

Dim path As String = "C:\questions.txt"
Dim alltext As String = File.ReadAllText(path)

Reading A Line At A Time

More often than not, you will want to process information from the file as it being read. At the very least, you are likely to want to store the information in variables or structures that you have set up for the purpose.

Dim path As String = "C:\questions.txt"
Dim sr As StreamReader = New StreamReader(path)
Dim lineoftext As String
While (Not sr.EndOfStream)
   lineoftext = sr.ReadLine()
End While

This program produces the same output as the first but allows you to work with a line at a time.

Notice that we close the stream at the end of processing.

Having A Go

  1. Write a program that reads a text file and counts the number of lines, words and characters.