Programming Lesson 9–Loading and Saving to Files

So far, all of our programs remember data only when they are running. If we close and open a program, then it runs as if it has never been run before, so any program where we enter data such as a list of names, will lose that information as soon as you close that program.

The final piece of our programming jigsaw, then, is to learn how to make data “persistent” or in simple terms – how to save stuff so we don’t lose it.

Loading and saving data enables us to do lots of useful things:

  • Save data from one use of the program to the next
  • Load in large amounts of information – saving you typing it in every time
  • Produce files from our programs which could be used for other things or even in other programs

Finally, remember that a good program is all about flexibility. It is highly unlikely you will ever truly know what the input to a program will be, so you can’t really hard code it in to your software (such as setting a user name or a password). If we write programs that read and write to files, we can use our code on totally different data sets at any time, thus making it far more flexible and useful.

Fortunately, loading and saving data in Visual Basic is very simple and there are only a few ways to really do it. For you, this just means you can copy and paste these sections of code in to your own program but you MUST understand it because…

  • You WILL need to understand how a file system works – so you know where files are saved, what a file path is and how to find information in a file system
  • You will need to know what each line of code does so you can explain it in your write up for any coursework
  • Finally, you will need to be able to change it so your data is read in to the correct array or you can manipulate the code to use lists if they are your data structure of choice.

Saving Data

Let’s look at the code and then go through it. You will find this code in the school shared area.

In this example, we will save an array of names to a text file. To show you how this works, we first need to set that array up:

Note that this is a console application, but would work in exactly the same way in a forms application.

If you can’t understand the code above then you have serious problems at this stage and, unfortunately, you have no choice but to go back several lessons and read up on variables and arrays.

The only thing of note here is the string currentDirectory and FileNameAndPath. These will be used to hold the folder (directory is another word for folder) that our program is running in. FileNameAndPath will hold the full path and file name of the text file we will create to save the names in.

Now we’ve set the program up, we can prepare to save the data.

This line uses built in libraries to find out where the program is running. We don’t have to do this, in fact….

Important note for you when you’re doing this:

You may wish to set the directory yourself. The only reason in this example I’m using the “current directory” is so that it works when you try out the code. I will explain the reasons behind this in the lesson, so make sure you pay attention and understand the reasons why we are saving the file in this example to the same directory as the program itself.

Just for completeness, the current directory will be something like “My Documents\Visual Studio\Projects\SavingToATextFile\Bin\Debug\”

Next, we create the full file name and path by taking the current directory and bolting the file name on the end that we want to use. Basically, this means we will create a text file called “OutputFile” in the current directory.

Finally, we use this piece of code to avoid some errors and strange behaviour. You should be able to work out exactly what’s going on – it simply checks if we already have a file called “OutputFile” and if we do, it deletes it. This avoids errors because the file already exists, is locked, open or similar.

Now we’re ready to actually save the data:

This is where a For… Each… loop really comes in to its own. We’ll break this down line by line:

This sets up our loop. Every time the loop goes round it takes the next element from the “names” array and stores it in a string called “name”

Next, take that name and add a “carriage return/line feed” to it. What does that mean? Simply that the output will have each name on a new line, rather than in one long line. It “presses enter” after each one.

The actual saving bit! WriteAllText actually adds the data to the file we are creating. It takes THREE values:

  • FileNameAndPath – the file it is writing
  • Name – the line to write in the file
  • True – this does something called “appending” which means it adds the line of data to the end of the file, rather than deleting the information in the file and starting again.

And that’s it. It actually is quite simple. Run the code, try it, change some names, open the text file after each try to see what happened.

Reading Data from a File

To read data we use something called a “stream reader” – something that reads data from, er, a stream of data…

The setup is virtually identical to the previous program so we will only focus on what’s new:

It’s slightly different this time.

First, an object called “SR” is created (this is short for stream reader). It is given the file name and path as you can see in the first line of code. This basically means we have an object that knows where our data file is and we can use it to read that data one line at a time.

This time we have to use a WHILE loop, because we don’t know how much data we will read in from a file. The condition looks slightly strange:

But basically, it means “while there is still data in the stream, continue”

The “peek” function has a look at the stream to see what’s there, but does so in a non-destructive way so we can actually read that data if there is any, or we can avoid an error if there is none. Clear as mud, as my gran used to say.

Finally, we save the data in an array – notice we are using the counter variable I to keep track of which element of the array we should use next. This is why lists are a lot nicer. If we used a list, we would simply do something like “names.add(sr.readline())” and have no need for a counter. You make your mind up which you fancy using…

Again, try it, use it, understand it, tweak it, add it to your programs.

That’s it. Remember, Google is your friend, reference EVERYTHING you use and don’t blindly copy and paste because if you don’t understand the code you’ll get zero marks for it.

You are on your own now…!