Tutorial: Reading and Writing to text file in VB.Net

Long overdue for another VB tutorial! So for all 4 of my faithful viewers, here is one of the most asked questions on coding forums, “How do I read from a text file in VB.Net?”. Let’s go over the simple task of reading and writing to a text file. You know the drill… Grab your favorite caffeinated beverage, put on some music (tonight is Sinatra’s greatest hits) and fire up Visual Studio. Here we go!

We’ll be using the StreamWriter and StreamReader Classes of the System.IO namespace to write and read, respectively. Double-click your blank form to add the default event and take you to code view. Let’s start by adding our import statement to the project:

Imports System.IO

That’ll save us some typing later on. We’ll start with reading from a file (could be a txt, an ini, or any other flat file). I’m gonna hit you with all the code for reading and then we’ll break it down:

Private Function ReadFile(ByVal myFile As String)
    Dim strContents As String
    Dim sr As StreamReader
    sr = New StreamReader(myFile)
    strContents = sr.ReadToEnd()
    Return strContents
End Function

So what I’ve done here is created a Function called ReadFile that accepts a String argument which we’ll use to pass in a file path to the file we’re going to read. We’ll be able to call it throughout our application any time we need to read the contents of any file. It will return a String value, strContents, which holds the contents of the file after it has been read. This will be the job of strContents as well. After that, the last thing we need before we get to the meat of the function is to declare and instantiate a StreamReader object which is going to expect 1 parameter, the argument we passed to the function.

The following lines are for declaring and instantiating the “holder” string and the StreamReader object. You can see how I’ve used the name of the argument for the parameter of the StreamReader:

Dim strContents As String
Dim sr As StreamReader
sr = New StreamReader(myFile)

Now the good stuff… and it’s only a one-liner! To read in the entire contents of the file and store it in our String object, all we need to do is call the ReadToEnd() method of the StreamReader object we created. You thought there’d be more to it? Well… there isn’t… “But I only got a few sips into my caffeinated beverage of choice and we’re almost done?”, you might be saying. I’m a heart-breaker.

Now all that’s left is the “garbage collection” aspect. Always remember to close your StreamReader by calling its Close() method once you’re done reading the contents.

You’ll want to enclose the call to the function inside a Try/Catch block just in case an error is thrown, such as bad file name, missing file, etc:

Catch ex as Exception
     'Something broke. Capture the error!
End Try

Some additional things to note when dealing with files. This tutorial covers reading the entire contents of a file at one time. It is also possible to read a file one line at a time using the ReadLine() method. By placing it within a loop, you can read all the lines and store them in an array, a List, or whatever you like.

In the next post, we’ll go over how to write to a file. Bottom’s up!

Comments welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *