Unit 14 Event Driven Programming
Persistent Data Using Text Files
© Peter Bilbie 2010-11

Contents

Introduction 3

Creating a Text File 4

Stream Reader/Writer Objects 5

Saving to a Text File 6

Exercise 10

Summary 12


Persistent Data - Using Text Files

Introduction

In the previous few weeks any data in any program we created was lost when the programs were closed. This is OK for small calculator type programs, but in a business environment where data is the lifeblood of the organization the loss of any data could be costly. We need to be able to make the data persist after an application has been terminated.

The most common approach to making business data persist is to use a database and to ensure that the integrity (correctness) of the business data most organizations have a database management system (DBMS) and database administrator. Most large scale organizations may employ database systems such as SQL Server or Oracle which can handle multiple instances of database files. SQL Server and Oracle databases are called relational databases because they are based on the theory of mathematical relations i.e. tables.

There are smaller relational databases such as MySQL and MS Access which are ideal to introduce students to the basics of relational databases and you will be introduced to MS Access later in the course.

There are other types of database systems used such as hierarchical, network and object-oriented but these are not as prevalent in business situations as relational databases and will not be covered as part of this course

However, there may be times when a simpler approach to the problem of making data persistent is required. For example, a program to save the monthly/weekly sales for a small company. The only data that needs to be saved is the week or month and the respective sales amounts i.e.

Week / Amount
1 / £2456
2 / £3432
3 / £9822
4 / £6634
5 / £7232
6 / £23645

We have already looked at using arrays (single/multi dimensional and dynamic) to contain data that is of the same data type and we have created a program to help us understand their use. We are now going to extend that program to include a simple, but effective procedure for saving the data by using a Text File.

Creating a Text File

We can create a text file in any folder by right-clicking inside the folder and selecting New->Text Document – see below

Give the text file a suitable name and retain the txt extension name – see below

To be able to access any external file from within VB .NET you can either provide the exact location address i.e. C:\My Documents\Experian…etc. or better still place the file in the Bin folder located in the project folder of the program you are using – see below

The Bin folder could contain many other files, the main one being the exe file for the program. If we add any file to the Bin folder, when we run the program VB looks in the Bin folder for any files that are used by the program. For example If we had a text file in the folder named pete.txt – see below – we would only need to supply the name of the file i.e. pete.txt, rather than the full address. This also applies to MS Access database files which we may be using in later sessions to demonstrate SQL

Stream Reader/Writer Objects

To access text files in VB .NET we can use two objects from the System.IO (system input/output) library – StreamReader and StreamWriter. As the names suggest the StreamReader will read from a file and the StreamWriter will write to a file. There are two ways to access the System.IO library - we can either make a reference to the library at the top of the code window by using the Imports operator i.e.

Imports System.IO

Public Class FrmArrays

Inherits System.Windows.Forms.Form

And declare a streamReader object with your code i.e.

Dim strReader As New StreamReader("pete.txt")

Or if you don’t ‘Import’ the System.IO library then you have to use the full address in the code i.e.

Dim strWriter As New System.IO.StreamWriter("pete.txt")

Saving to a Text File

System.IO deals with all the file handling inputs and outputs. However you may find problems using the methods and properties of System.IO if you are not working on the computers ‘C’ drive. If you are working on a network you will probably have restricted access rights to certain folders and drives which could cause problems with the program not working as it should. Ideally programmers developing applications should have administrator’s rights. Programs running on a network often generate the following message

This will not prevent you using the program but it will almost certainly not work entirely as expected.

Using the Weekly Sales Figures program from the ‘Arrays’ tutorial we will add the code needed to save the data to a text file – for this example I will use the text file ‘pete.txt’ which I have stored in the bin file of the project

With the ‘Array’ program, when the program is loaded all the weeks sales in the list box are all defaulted to 0 using the following code in the Form Load event of the form:

For i = 0 To 51

mbSales.Items.Add(i + 1)

sales(i, 0) = i + 1

lstArrays.Items.Add("Week " & sales(i, 0) & " = " & _

Format(sales(i, 1), "c"))

Next

cmbSales.SelectedIndex = 0

The result is shown below:

If we use a text file to save the data then if we had an empty file before we started the program then we would see a blank list box – see below:

With a text file with saved data then the form would look as shown below

To achieve the above we will need to add the following code to the Form Load event of the form:

The code explained:

Line:

114 – Event header

115 – Create a new object of the streamReader class from the System.IO library and

pass the text file as a parameter

116 – Declare a string variable to hold the data being read from the file

117 – Declare an integer variable to be used as an index in both loops

118 – The Do While loop checks the value of the Peek function of the streamReader

object – if there is data in the file Peek will return the next character to be read. If there is no more data or the file is empty Peek will return -1

120 – Use the ReadLine function of the streamReader object to assign the current line of

the file to the string variable myString

121 – Assign the first 3 characters of the string MyString to the two dimensional array

element sales. The first index of the array is set by the current value of ‘i’ and

the second index is using the value 0. The first 3 characters are extracted using

the Substring function of the Sting class. This function takes either one or two

integer parameters – if one integer parameter is set then the function will return a

string that begins from the position of the character indicated by the parameter to

the end of the string i.e. using the string ‘Polymorphism’ assigned to the string

MyString the substring MyString.Substring (4) will return ‘morphism’ – it will start

at the fifth character (remember, numbering starts at 0 therefore the substring will

start at the 5th character.

If we use the second parameter – as we have in this instance i.e. MyString.Substring(0,2) – the function will return the number of character indicated by the second parameter starting from the position indicated by the first parameter i.e. using the example abovber MySting.Substring (0,3) will return ‘Poly’

122 – Using the second version of the MyString function, assign the remaining

characters of the string MyString to the array element indicated by the value of ‘i’ and 0

124-5 – Display the values of the two array elements in the list box

126 – Increment the value of ‘i’ – otherwise the first array values will be over written and

the values of the remaining array elements will be 0. To demonstrate this if we edit out the line 126 - i += 1 – and assign the value of the first element of the array to the textbox txtArray.text i.e. txtArray.Text = sales(0, 1) – after the loop the value will be 0

127 – Finish the loop

128 – Close the stremReader so that it can be used again

130-132 – Another for loop that adds the numbers 1 – 52 to the combo box

133 – sets the combo box to the first item in the list – in this instance 1

Exercise

Using the student grades example from week 6 – controlling program flow part 1 – write a small program that will allow the user to enter student marks, work out the grade and save the student name, grade and mark to a text file as a comma separated list. The name, mark and grade also need to be formatted and displayed in a list box – see below

To help you with this exercise there is another string manipulation function that may be of use to you – the Split function. This function takes a string and splits it into any words or phrases that are separated by a given separator i.e. a comma and returns an array without the separators. It takes two parameters, the string and the separator type (in speech marks) – see below

Split (“The, Man, In, The Moon”,”,”)

You will need to declare an array variable to assign the split string to i.e.

Dim myArray (3) As String

myArray = Split (“The, Man, In, The Moon”,”,”)

You will need to determine how many array elements there will be in the string – the string above has four words separated by commas so the array needs four elements i.e. myArray (3) – 0 to 3 – four elements

If we had separate textboxes on a form we would be able to assign each separate element to a textbox i.e.

myString = “The, Man, On, The Moon”

myArray = Split(myString, ",")

txtFirst.Text = myArray(0)

txtSecond.Text = myArray(1)

txtThird.Text = myArray(2)

txtFourth.Text = myArray(3)

The result would be:

Summary

In this session we covered:

·  Using databases to retain data

·  Using simple text files to save data

·  Using the Bin file to save the text files

·  Using the streamWriter object of the System.IO class to write data to a text file

·  Using the stremReader object of the System.IO class to read data from text files

·  Using the Split function to manipulate comma delimited files

In the following session we will begin to look at creating our own classes and objects

© Peter Bilbie 2010-11 Page 12 of 12