Chapter 12 - Reading data from a text file. (file.txt)

(edited from UK Home&Learn web site )
Note that the second part of this requires you to have completed Chapter 16 - Arrays.

The ability to open up a text file and read its contents can be very useful to you in your programming experimentation. In this tute you will see how to open a text file and read contents into a text box, then how to read contents into an array.

To open up a text file, you need to create something called a "StreamReader". This, as its name suggests, reads streams of text. The StreamReader is an object available to System.IO. You create a StreamReader like this:

Dim FILE_NAME As String = "C:\test.txt"

Dim objReader As New System.IO.StreamReader(FILE_NAME)

The first line just sets up a string variable called FILE_NAME. We store the path and name of our text file inside of the string variable:

= "C:\test.txt"

We're saying that there is a text file called test which is at the location (path) "C:\". In this case we are specifying the file name but you could read it in from a text box.

You set up the StreamReader to be a variable, just like a String or Integer variable. But we're setting up this variable differently:

Dim objReader As New System.IO.StreamReader(FILE_NAME)

We've called the variable objReader. Then, after the "As" word comes "New". This means "Create a New Object". The type of object we want to create is a StreamReader object:

System.IO.StreamReader

System is the main object. IO is an object within System. And StreamReader is an object within IO.

StreamReader needs the name of a file to Read. This goes between a pair of round brackets:

System.IO.StreamReader(FILE_NAME)

VB will then assign all of this to the variable called objReader. So instead of assigning say 10 to an Integer variable, you are assigning a StreamReader to a variable. 

Read To End

But this won't do you any good. We haven't actually opened the text file yet. We've just told VB where the text file is and what object to open it with. You do the opening like this:

TextBox1.Text = objReader.ReadToEnd

Now that objReader is an object variable, it has its own properties and methods available for use (in the same way that the textbox has a Text property).

File Not Found errorOne of the Methods available to our new StreamReader variable is the ReadToEnd method. This will read the whole of your text, right to the end. We're then popping this in a textbox.

Let's test all this theory out. But we need to note that if the file does not exist in the specified location, you will get an error much something like this:

So we will test that the file exists first, as you will see when you look at the code below.

Do the following:

· Download test.txt to your C drive

Start a new project

· Add a textbox to your new form, and just leave it on the default Name of Textbox1

· Set its MultiLine property to True

· Add a Button to your form

· Double click the button and add the following code for it:

Dim FILE_NAME As String = "C:\test.txt"If System.IO.File.Exists(FILE_NAME) = True Then
Dim objReader As New System.IO.StreamReader(FILE_NAME)
TextBox1.Text = objReader.ReadToEnd
objReader.Close()
Else
MsgBox("File Does Not Exist")
End If

The last line closes the StreamReader we set up. You have to close your stream objects after you’ve used them, otherwise you’ll get error messages.

When you’re done, run your programme and click your Button.

We've now wrapped up our code in an If Statement. The first line of the If Statement is this:

If System.IO.File.Exists(FILE_NAME) = True Then

This tests to see whether or not a file exists. Again, you start with System.IO. Then you access another object of System.IO - the File object. This has a method called Exists. In between the round brackets, you type the name (or variable) of the file you want to check. The value returned will either be True (if it does exists), or False (if it doesn't).

If the file exists then we can go ahead and create our StreamReader; If it doesn't, we can display a error message for the user.

So that your programme will work download test.txt to your computer, in the main C:\

When you have done that, run your programme. Click the button  and you should see the text from your file appear in the textbox. (If you get the error message again, it means you haven't copied the file to the right place.)

Reading in a file line by line

Quite often, you don't want to read the whole file at once. You want to read it line by line. In which case, instead of using the ReadToEnd method, as we did in the previous section, you can use the ReadLine method:

The ReadLine method, as its name suggests, reads text one line at a time. In order to do this, though, you need to use a loop. You can then loop round each line and read it into a variable. Here's a coding example:

Dim TextLine As String

Do While objReader.Peek() <> -1
TextLine = TextLine & objReader.ReadLine() & vbNewLine
Loop

The first line of the Do While loop is rather curious:

Do While objReader.Peek() <> -1

The Peek method takes a peek at the incoming text characters. It's looking ahead one character at a time. If it doesn't see any more characters, it will return a value of minus 1. This will signify the end of the text file. Our loop checks for this minus 1, and bails out when Peek has this value.

Inside the loop, we're reading each line from the text file and putting into new variable called TextLine. (We're also adding a new line character on the end. Delete the & vbNewLine and see what happens).

objReader.ReadLine()

So the ReadLine method reads each line for you, instead of the ReadToEnd method which gets the whole of the text file.

But what you are doing in the Do Loop is building up your variable with lines of text that are pulled from your text file. Once you have pulled all the text from your file, you can then put it into the text box. Here's our programme once more, with the new code:

Dim FILE_NAME As String = "C:\test1.txt"
Dim TextLine As String

If System.IO.File.Exists(FILE_NAME) = True Then

Dim objReader As New System.IO.StreamReader(FILE_NAME)

Do While objReader.Peek() <> -1
TextLine = TextLine & objReader.ReadLine() & vbNewLine
Loop

Textbox1.Text = TextLine

Else

MsgBox("File Does Not Exist")

End If

So inside the loop, we go round building up the TextLine variable. Once all the file has been read (when Peek() has a value of -1), we then place it into Textbox1.

  Reading into an Array

With some small modifications the above code can be altered so that the text file is read line by line into an array, then displayed line by line in a listbox. Create a new form as per the picture with the following controls.

Listbox1

Button – cmdShow – text Open File

Button – CmdDisplay – text Show Array

To simplify matters we have made two Public Variables – an array “textArray(10)” and “numlines” to keep track of how many records we read in. These variables will be shared between the code to read in the file and the segment to display it in the listbox.

Switch to code view and paste in these declarations right under Public Class Form1

Public textarray(10) As String

    Public numlines As Integer

Now double click the CmdShow button and paste in

Dim FILE_NAME As String = "C:\test1.txt"

        Dim TextLine As String = ""

        If System.IO.File.Exists(FILE_NAME) = True Then

            Dim objReader As New System.IO.StreamReader(FILE_NAME)

            numlines = 0

            Do While objReader.Peek() <> -1

                textarray(numlines) = objReader.ReadLine()

                numlines = numlines + 1

            Loop

        Else

            MsgBox("File Does Not Exist")

        End If

Double Click cmdDisplay button and paste in the following:

Dim count As Integer

        count = 0

        Do While count <= numlines

            ListBox1.Items.Add(textarray(count) & vbNewLine)

            count = count + 1

        Loop

Make sure that you have copied the text1 file to your C drive, then test by fist clicking the button to load the file, then the other to display it.

Note that we have not separated the two items on each line, but you get the idea.