VB .NET Chapter 9 Working with Text Files

Text Files and VB .NET

There is a very useful object in VB.NET called System.IO (the IO stands for Input and Output). You can use this object to read and write to text files.
We're going to be having a closer look at objects (and what System is) in the next section. For now, let's just see how to open up a text file using the System.IO object.
First, here's an explanation of just what we mean by "text file".

What is a Text File?

The files on your computer all end in a three letter extensions. Microsoft Word files will have a different three letter extension from Microsoft Excel files. The extension is used to identify one file type from another. That way, Excel won't try to open Word files, or vice versa. You can just write some code to strip the last three letters from the file name, and then check that these three letters are the ones you want. Rather like the code you wrote to strip the last three letters from an email address.
Text files have an extension that ends in .txt. The Windows operating system gives you a good, basic Text Editor in Notepad. The Notepad programme allows you to save files with the .txtextension. In other words, as Text Files. These Text Files can then be opened by a wide variety of programmes.
A simple text file like this is called a Sequential File, and that is what we will be opening here. So let's begin.

How to Open a Text File in VB .NET

The ability to open up a text file and read its contents can be very useful to you in your programming life. You might have a text file containing quiz questions and answers, for example. You could read the questions and answers from a text file and create your own "Who wants to be a Millionaire" game. Or you might want to save some data associated with your programme, and then open it up again when the programme starts. Well see how to open up a text file in VB .NET right now. In a later section, you'll learn how to save data to a text file.


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 (if you have Windows XP, you can just use C:\test.txt instead of the longer file name we use for these text file tutorials):
Dim FILE_NAME As String = "C:\Users\Owner\Documents\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:\Users\Owner\Documents\test.txt"
We're saying that there is a text file called test which is at the location (path) "C:\".
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
Sysytem 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).
One 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. Do the following:
  • 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:\Users\Owner\Documents\test.txt"
Dim objReader As New System.IO.StreamReader( FILE_NAME )
TextBox1.Text = objReader.ReadToEnd
objReader.Close()
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 errors messages.
When you’re done, run your programme and click your Button.
Unless you already have a file called test.txt at the location specified you’ll get this error message popping up, though 2012 and 2013 users will see the message in a diferent format:
FileNotFound Error message in VB NET
The last line spells it out clearly: Could not find file "C:\Users\Owner\Documents\test.txt". So we were trying to read a text file that doesn't exist.


Does the File Exist?

You can, though, test to see if the file exists. If it does, you can open it; if not, you can display an error message. Amend your code to this (the new lines are in bold):
Dim FILE_NAME As String = "C:\Users\Owner\Documents\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>
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 exist 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, there is a file below called "test.txt". Download this to your computer, either in the main C:\ folder for XP users, or the Documents folder if you have Vista/Windows7. (Right click the file and select Save Target As (IE), or Save Links As (Firefox):
When you have done that, run your programme again. Click the button once more, 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 a Text 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 theReadLine 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. (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.
Once you have a line of text in your variable, though, it's up to you to parse it. For example, suppose the line of text coming in from the text file was this:
"UserName1, Password1, UserName2, Password2"
You would then have to chop the line down and do something which each segment. VB won't do this for you! (But you saw how to do this in the last section, when you used things like Split andSubstring.)
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 highlighted in bold text:
Dim FILE_NAME As String = "C:\Users\Owner\Documents\test.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.

How to Write to a Text File in VB .NET

Writing to a text file is similar to reading a text file. Again we use System.IO. This time, instead of using the StreamReader we use the StreamWriter. The StreamWriter is used to write a stream of text to a file.
Add another Button to the form you've been working on. Set the Text property of the button to "Write to File". Double click your new button to open up the coding window. Add the following:
Dim FILE_NAME As String = "C:\Users\Owner\Documents\test2.txt"
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter( FILE_NAME )
objWriter.Write( TextBox1.Text )
objWriter.Close()
MsgBox("Text written to file")

Else
MsgBox("File Does Not Exist")
End If
Run your programme, and then click your new button.
Unless you have a file called "test2.txt", you should see the message box display: "File Does Not Exist."
Once again, VB insists that the file must exist before it can actually do something with it. Which is not unreasonable!
Stop your programme and change this line:
Dim FILE_NAME As String = "C:\Users\Owner\Documents\test2.txt"
To this:
Dim FILE_NAME As String = "C:\Users\Owner\Documents\test.txt"
In other words, just change the file name back to test.txt. (Hopefully, you haven't deleted thetest.txt file from your hard drive!)
Run your programme again. Type something into the textbox, and then click your button. You should see the message box "Text written to file" appear.
But notice that if you open up the text file itself, any text you had previously will be gone - it has been overwritten, rather than appended to. (We'll see how to append text to a file shortly.)
Let's have a look at the code we wrote, though.
Once again, we check to see if the File Exists. If it's True that the file exists, then the first line that gets executed is setting up our variable:
Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
It's almost the same as last time. Only two things have changed: we created a new variable name,objWriter, and we're now using StreamWriter instead of StreamReader. Everything else is the same.
To write the text to our file, we've used this:
objWriter.Write( TextBox1.Text )
After the name of our variable (objWriter), we typed a full stop. The drop down box appeared showing available properties and methods. The "Write" method was chosen from the list. In between round brackets, you put what it is you want VB to write to your text file. In our case, this was the text in Textbox1. You can also do this:
objWriter.Write( "Your Text Here" )
The above uses direct text surrounded by double quotes. This is also acceptable:
Dim TheText As String = "Your Text Here"
objWriter.Write( TheText )
This time, we've put the text inside of a variable. The name of the variable is then typed inside of the round brackets of "Write".
But you don't have to write the whole text at once. You can write line by line. In which case, selectWriteLine from the available properties and methods. Here's an example of how to use WriteLine:
Dim FILE_NAME As String = "C:\Users\Owner\Documents\test.txt"
Dim i As Integer
Dim aryText(4) As String

aryText(0) = "Mary WriteLine"
aryText(1) = "Had"
aryText(2) = "A"
aryText(3) = "Little"
aryText(4) = "One"

Dim objWriter As New System.IO.StreamWriter( FILE_NAME )
For i = 0 To 4
objWriter.WriteLine( aryText(i) )
Next
objWriter.Close()
The error checking code has been left out here. But notice the new way to write text to the file:
objWriter.WriteLine( aryText(i) )
We're looping round and writing the contents of an array. Each line of text from the array gets written to our text file. But each line is appended. That is, the text file doesn't get erased after each line has been written. All the lines from the array will be written to the text file. However, if you were to run the code a second time then the contents of the file are erased before the new WriteLine() springs into action. In other words, you'd only get one version of "Mary WriteLine had a little one" instead of two.

Appending Text to a File in VB .NET


There will be times when you won't want to erase all the text from your file. You'll only want to add text to what you currently have. In which case you need to Append.
Appending text to your file is quite easy.
When you set up the object variable for the StreamWriter, which you did here, you just typed the name and path of the file:
Dim objWriter As New System.IO.StreamWriter( FILE_NAME )
To append text to a file, you type a comma after your file name then type the word True:
Dim objWriter As New System.IO.StreamWriter( FILE_NAME, True )
If you want to add some text to the file, you need that True value. If you leave out the True or False, a new file is not created.
Here some code we wrote to that appends text to the file:
Dim FILE_NAME As String = "C:\Users\Owner\Documents\test.txt"
Dim i As Integer
Dim aryText(4) As String

aryText(0) = "Mary WriteLine"
aryText(1) = "Had"
aryText(2) = "Another"
aryText(3) = "Little"
aryText(4) = "One"

Dim objWriter As New System.IO.StreamWriter( FILE_NAME, True )
For i = 0 To 4
objWriter.WriteLine(aryText(i))
Next
objWriter.Close()
MsgBox("Text Appended to the File")
The lines that have changed are in bold. But, as you can see, not much has changed! But try both version and see how they work.

Creating a file if it doesn't exist

If you want to create a file if one doesn't exist, the process is again quite simple:
Dim objWriter As New System.IO.StreamWriter( FILE_NAME, False )
This time, we've just added the word "False" to the end of FILE_NAME. This will ensure that a new text file is created if one doesn't exist.

How to Copy a File in VB .NET

You can also copy a file that you've created. This time, we don't need the StreamWriter or StreamReader of System.IO. We need the File object:
System.IO.File
This just means "System.IO has an object called File. Use this File object".
File has it's own properties and methods you can use. One of these is Copy. Here's some code that makes a copy of our test file .
Dim FileToCopy As String
Dim NewCopy As String

FileToCopy = "C:\Users\Owner\Documents\test.txt"
NewCopy = "C:\Users\Owner\Documents\NewTest.txt"

If System.IO.File.Exists( FileToCopy ) = True Then
System.IO.File.Copy( FileToCopy, NewCopy )
MsgBox("File Copied")

End If
The file we want to copy is called "test.txt". We've put this inside of a string variable calledFileToCopy. The name of the new file we want to create, and its location, are assigned to a variable called NewCopy.
Next, we have to check to see if the file we're trying to copy exists. Only if it does should we go ahead and copy it. You've met this code before. Inside of the If Statement, we have this:
System.IO.File.Copy( FileToCopy, NewCopy )
We use the Copy method of System.IO.File. In between the round brackets, you first type the name of the file you want to copy. After a comma, you then type the name of the new file and its new location.

How to Move a File with VB .NET

You move a file in a similar manner as you did to Copying a File - specify a source file and a new destination for it. This time, we use the Move method of System.IO.File. Here's some code:
Dim FileToMove As String
Dim MoveLocation As String

FileToMove = "C:\Users\Owner\Documents\test.txt"
MoveLocation = "C:\Users\Owner\Documents\TestFolder\test.txt"

If System.IO.File.Exists( FileToMove ) = True Then
System.IO.File.Move( FileToMove, MoveLocation )
MsgBox("File Moved")

End If
The above code assumes that you have created a folder on your hard drive called "TestFolder":
MoveLocation = "C:\Users\Owner\Documents\TestFolder\test.txt"
The file called test.txt will then be moved inside of this new location. You can give it a new name, if you want. In which case, just change the name of the file when you're moving it:
MoveLocation ="C:\Users\Owner\Documents\TestFolder\NewName.txt"
Again though, the thing to type in the round brackets of the method is first the Source file, then the Destination.
System.IO.File.Move( FileToMoveMoveLocation )

How to Delete a File in VB .NET

Deleting a file is quite simple - but dangerous! So be very careful when you're trying out this code. Make sure the file you're going to delete is not needed - you won't be able to restore it from the recycle bin!
To delete a file from your computer, you use the Delete method of System.IO. Here's some new code for you to try:
Dim FileToDelete As String
FileToDelete = "C:\Users\Owner\Documents\testDelete.txt"
If System.IO.File.Exists( FileToDelete ) = True Then
System.IO.File.Delete( FileToDelete )
MsgBox("File Deleted")

End If
First, we've set up a string variable called FileToDelete. We've then assigned the name of a file to this variable - "C:\testDelete.txt". (We created this file first, and made sure that it was safe to junk it!)
Next, we test to see if the File Exists. In the IF Statement, we then had this:
System.IO.File.Delete( FileToDelete )
After selecting the Delete method, you type the name of the file you want to get rid of. This goes between a pair of round brackets.
And that's it! That's all you need to do to delete a file from your computer, never to see it again. So be very careful when you test out the code!

OK, enough of Text Files. In the next section, we'll look at Functions and Subs.

Comments