Programming for Computing 07 - 08

Chapter: Files

Module Admin   Contents, Index   Schedule  
1: Intro to VB    2: First Program and Projects    3: Variables, assignment, Strings    4: Type Conversion, InputBox, Constants    5:Built-in Functions    6: If - decisions    7: Loops - while, for    Example - find smallest    8: Scopes: local, global    9: Writing Procedures.Parameters, Functions   
10: Objects    11: Design    12: Testing    13: Graphics    14: Controls and events    15: Listboxes    16: Arrays    17: Files    18: The Command Line   

Appendices(links etc)   Additional Lectures    Tutorials (not in printed notes)     Selected solutions (not in printed notes)     Assignments    Additions and Errata   

new

The  schedule page has info on what we will do each week.

 


Section 17.0

This chapter (From Visual Basic.Net for Students) explains:
  • what a text file is;
  • how to read and write data to files;
  • how to manipulate folder paths and names.

Introduction

You have already made use of files, in the sense of having used the IDE to create files containing VB programs, and having used Windows to view a hierarchical structure of folders (directories). In this chapter, we will look at the nature of the information you may choose to store in files, and how you can write programs to manipulate files.

Initially, let us clarify the difference between RAM (random-access memory) and file storage devices (e.g. disks, hard disk drives and CD-ROMs). Storage capacity is measured in bytes in all these cases. There are several major differences between RAM and file storage:

  • RAM is used to store programs as they execute. They are copied from a file storage device immediately before execution.
  • The time to access an item in RAM is much faster.
  • The cost of RAM is higher (megabyte for megabyte).
  • Data in RAM is temporary: it is erased when power is switched off. File storage devices can hold data permanently.
The capacity of file storage devices is higher. CD-ROMs have a capacity of around 650Mbyte (megabytes) and DVD (Digital Versatile Disks) have a capacity of 4.7 Gbyte (gigabyte, 1024 Mbyte). Both CD-ROM and DVD have writable versions. Typical hard drives can hold around 80 Gbyte, and the lowly floppy holds around 1.4Mbyte. However, technology is evolving rapidly - the race is to create cheap fast, small storage devices that modern computer software requires, especially in the area of high-quality moving images and sound.

 


Section 17.1

The essentials of streams

Streams let us access a file as a sequence of items. The term 'stream' is used, in the sense of a stream of data flowing in or out of the program. Let us introduce the jargon, which is similar in most programming languages. If we wish to process the data in an existing file, we must
  1. Open the file.
  2. Read (input) the data item-by-item into variables.
  3. Close the file when we have finished with it.
To transfer some data from variables into a file, we must:
  1. Open the file.
  2. Output (write) our items in the required sequence.
  3. Close the file when we have finished with it.
Note that, when reading from a file, all we can do is read the next item in the file. If for example, we only needed to examine the last item in a file, we would have to code a loop to read each preceding item in turn, until the required item is reached. For many tasks, it is convenient to visualize a text file as a series of lines, each made up of a number of characters. Each line is terminated by an end-of-line marker, consisting of either the line- feed character, or the carriage-return character, or both of these. Your response to this might be to say "I just hit Enter at the end of a line!". Behind the scenes, Windows software will put a line-feed character and a carriage-return character at the end of each line. Most of this intricacy is hidden by VB.

As well as files containing lines of text, VB can also manipulate files containing binary data, such as images. However, such data is usually arranged in a more complicated format within files.

We shall make use of the VB classes that allow us to access a file line-by- line, as text strings. This is particularly useful, because many applications (such as word-processors, text editors and spreadsheets) can read and write such files.

NOTE - here we use the term 'method' - this has the same meaning as 'procedure' or 'function'

 


Section 17.2

The StreamReader and StreamWriter classes

To read and write lines of text, we will use:
  • The ReadLine method of StreamReader. This reads a whole line of text into a string, excluding the end-of-line marker. (If we need to split the line into separate parts, we can use the Split function described in Chapter 16.)
  • The StreamWriter class. This has two main methods: Write and WriteLine. They both write a string to a file, but WriteLine adds the end-of-line marker after the string. We can also use WriteLine with no string argument, where an end-of-line marker is written to the file.
  • The OpenText and CreateText methods of the File class. These are shared methods, and provide us with a new instance of a text stream. A selection of other methods and properties of the File class is covered later in this chapter.
The file classes are in the System.IO namespace. This is not automatically imported, so we must put:
Imports System.IO
at the very top of all our file-processing programs.

 


Section 17.3

File output

The File Output program opens a file and writes three lines to it. The user- interface only consists of a single button, so is not shown. Note that if your system prevents you from accessing the C: area, use e.g. C:\temp\myfile.txt.

Here is the code:


Imports System.IO               ' at the very top, above the 'class' line

Private Sub Button1_Click( _
                    ByVal sender As System.Object, _
                    ByVal e As System.EventArgs) _
                    Handles Button1.Click
    ' write some lines of text to the file
    Dim outputStream As StreamWriter = _
                     File.CreateText("c:\myfile.txt")
    outputStream.WriteLine("This file will")
    outputStream.WriteLine("contain  3")
    outputStream.WriteLine("lines of text.")
    outputStream.Close()
End Sub
Firstly we create and open the file:

Dim outputStream As StreamWriter = _
                 File.CreateText("c:\myfile.txt")
Here, we make use of the shared method CreateText from the File class. This creates a new StreamReader object for us, and opens the file. Note that there are two items which refer to the file:
  • There is a string which specifies the file name that the operating system uses when it displays folders: "c:\myfile.txt". Alter this path if you wish to create the file in a different place. If you omit the folder name and just use myfile.txt, then the file will be created in a folder named bin, which is a sub-folder of your current VB project.
  • There is a variable which we chose to name as outputStream. It is an instance of the class StreamWriter, which provides us with the WriteLine method. The use of CreateText associates outputStream with the file "c:\myfile.txt".
To actually write a line of text to the file, we use WriteLine, as in:
outputStream.WriteLine("This file will")
If the data we wish to place in the file is typed-in by the user - perhaps in a text box, we would put:
outputStream.WriteLine(TextBox1.Text)
If the file existed already, its original contents will be erased, and replaced by the three lines.

Finally, we close the file:

outputStream.Close()
This ensures that any data in transit is actually placed in the file, and also allows the file to be re-opened for reading or writing.

In summary, our file output process was:

  • to open the file "C:\myfile.txt";
  • to output (write) some strings to the file;
  • to close the file.

SELF-TEST QUESTION 1
Explain what the following code does:
Dim lines, stars As Integer
Dim fileName As String = "c:\pattern.txt"
Dim streamOut As StreamWriter = _
    File.CreateText(fileName)
For lines = 1 To 10
    For stars = 1 To lines
        streamOut.Write("*")
    Next
    streamOut.WriteLine()
Next
streamOut.Close()

(answer at end)  


Section 17.4

File input

Here we examine the program named File Input, which opens a file, inputs its contents, and displays it in a text box. b> The screenshot (taken after the button was clicked) is given in figure 1. Here is the code:
Private Sub Button1_Click( _
                    ByVal sender As System.Object, _
                    ByVal e As System.EventArgs) _
                    Handles Button1.Click
    'read the file line-by-line
    Dim inputStream As StreamReader = _
                       File.OpenText("c:\myfile.txt")
    Dim line As String
    line = inputStream.ReadLine()
    While line <> Nothing
        TextBox1.AppendText(line & VbCrLf)
        line = inputStream.ReadLine()
    End While
    inputStream.Close()
End Sub

[files1.jpg]
fig 1 - Screenshot of File Input program.

The code is contained in the method Button1_Click. The file we choose to input is the one that was created by the previous File Output program, containing three lines of text.

First, we create a stream to access the file:

Dim inputStream As StreamReader = _
                   File.OpenText("c:\myfile.txt")
(If the file we specify cannot be found, an exception will be produced. For now, we ignore this possibility, but discuss it later in this chapter.)

Then we use ReadLine to input the series of lines in the file, appending each one to our text box. There is one crucial point here: we don't know how many lines are in the file, so we set up a loop which terminates when there is nothing more to read:

line = inputStream.ReadLine()
While line <> Nothing
    TextBox1.AppendText(line & VbCrLf)
    line = inputStream.ReadLine()
End While
When ReadLine runs out of lines to read, it returns Nothing, and this is assigned to line. Nothing is a keyword in VB, indicating that the object does not exist.

Note that we have used ReadLine twice. The first ReadLine prior to the loop is needed so that the first time While tests line, it has a value.

Each line is placed at the end of any existing text already in the text box, by using AppendText. Because ReadLine does not provide us with the end-of- line characters, we need to use VbCrLf. If we omitted this, the text box would contain one long line, with no breaks.

Reading a file line-by-line allows us to process each line individually (as we do in the File Search program below). Alternatively, it might be more appropriate to read the whole file into one long string, complete with end- of-line markers. In this case, VB provides us with a method named ReadToEnd, which we use for the text editor program shown later.

In summary, the program:

  1. opens a file;
  2. inputs lines from the file and appends them to the text box, as long as the end of the file is not reached;
  3. closes the file.

SELF-TEST QUESTION 2
The following code is meant to display the length of each line in a file. Explain any problems.

Dim fileName As String = "c:\tempvb7.txt"
Dim stream As StreamReader = File.OpenText(fileName)
Dim line As String

line = stream.ReadLine()
While line <> Nothing
    line = stream.ReadLine()
    TextBox1.AppendText("length: " & line.Length & ",")
End While
stream.Close()
 


SELF-TEST QUESTION 3
Explain any problems in this code:
Dim fileName As String = "c:\tempvb7.txt"
Dim stream As StreamReader = File.OpenText(fileName)
Dim line As String
line = stream.ReadLine()
While line <> Nothing
    TextBox1.AppendText(line)
End While
stream.Close()

 


Section 17.5

File searching

Searching a file for an item that meets some specified criteria is a classic task. Here we will construct a program which searches a file of exam marks, which takes the form:

J.Doe, 43 , 67
D.Bell ,87,    99
M.Parr, 54, 32
J.Hendrix, 67,43
etc...
We might create this file by writing and running a VB program, or with a text editor. Each line is split into three areas, separated by commas. However, we will allow for extra spaces. In data processing, such areas are known as fields. The program will allow us to enter a filename, and to enter a student name, which we assume is unique. If the names are not unique, we would have to introduce an extra field to hold a unique identification number for each person. The program will search the file, and display the marks for our chosen student. The code we need to add to our previous file input example is a While which terminates when the end of the file is encountered or when the required name is found. We will use the Split function to separate the three fields.

Because there are two ways that the loop can terminate, we introduce an additional variable, found, to indicate whether the item was found or not. Note that we expect that the item will sometimes not be found - it is not regarded as an error, and we code this with If rather than using exceptions.

The informal English structure of the search is:

found = False
While (more lines to read) And found = False
    read line
    split line into three fields
    If first field matches name Then
         found = True
         display rest of fields in labels
    End If
End While
If Not found
    display a warning
End If
We have provided a search button, which causes the file to be opened and searched. The user can select any file for searching. Figure 2 shows the screenshot, and here is the code.
Private Sub Button1_Click( _
                    ByVal sender As System.Object, _
                    ByVal e As System.EventArgs) _
                    Handles Button1.Click
    Dim line As String
    Dim words(3) As String
    Dim found As Boolean = False
    Dim inputStream As StreamReader

    'clear any previous results
    Result1Box.Text = ""
    Result2Box.Text = ""

    If FileNameBox.Text = "" Then
        MessageBox.Show("Error:  missing file name!")
    ElseIf StudentNameBox.Text = "" Then
        MessageBox.Show("Error: missing student name!")
    Else
        inputStream = File.OpenText(FileNameBox.Text)
        line = inputStream.ReadLine()
        While (line <> Nothing) And found = False
            words = Split(line, ",")   'use , as separator when splitting into array
            If Trim(words(0)) = StudentNameBox.Text Then
                Result1Box.Text = Trim(words(1))
                Result2Box.Text = Trim(words(2))
                found = True
            Else
                line = inputStream.ReadLine()
            End If
        End While
        If Not found Then
            MessageBox.Show(StudentNameBox.Text & " not found")
        End If
        inputStream.Close()
    End If
End Sub
[files2.jpg]
fig 2 - screenshot of File Search program


SELF-TEST QUESTION 4
Amend the search program so that the searching is done in a case-insensitive way (i.e. so that john matches john, John and JOHN).


SELF-TEST QUESTION 5
Explain the problem that would arise if we re-coded our search loop with Or, as in:

    While (line <> Nothing) Or found = False


 


Section 17.6

Files and exceptions

File input-output is a major source of exceptions. For example, the file name supplied by the user might be incorrect, the disk might be full, or the user might remove a CD-ROM whilst reading is in progress. We can minimize the effects of incorrectly-entered file names by using file dialogs (covered later), which let the user browse folders and click on file names, rather than typing the names into text boxes. But exceptions will still occur. Here we examine exceptions as they relate to files.

A number of exceptions can be thrown when we access files. Here is a selection:

  • the File.OpenText method can throw a number of exceptions. We shall single out FileNotFoundException in particular;
  • the ReadLine method of class StreamReader an d the WriteLine method of class StreamWriter can throw an IOException, along with other classes of exceptions.
Here is another version of the search program, with exception-handling:
Private Sub Button2_Click( _
                    ByVal sender As System.Object, _
                    ByVal e As System.EventArgs) _
                    Handles Button2.Click
    'search the file - with exception-handling
    Dim line As String
    Dim words(3) As String
    Dim found As Boolean = False
    Dim inputStream As StreamReader

    'clear any previous results
    Result1Box.Text = ""
    Result2Box.Text = ""

    If FileNameBox.Text = "" Then
        MessageBox.Show("Error:  missing file name!")
    ElseIf StudentNameBox.Text = "" Then
        MessageBox.Show("Error: missing student name!")
    Else
        Try
            inputStream = File.OpenText(FileNameBox.Text)

            line = inputStream.ReadLine()
            While (line <> Nothing) And found = False
                words = Split(line, ",")
                If Trim(words(0)) = StudentNameBox.Text Then
                    Result1Box.Text = Trim(words(1))
                    Result2Box.Text = Trim(words(2))
                    found = True
                Else
                    line = inputStream.ReadLine()
                End If
            End While
            If Not found Then
                MessageBox.Show(StudentNameBox.Text _
                                & "  not found")
            End If

            inputStream.Close()
        Catch problem As FileNotFoundException
            MessageBox.Show("Error - file not found: " _
                            & FileNameBox.Text _
                            & ".  Re-enter name.")


        Catch problem As Exception
            MessageBox.Show("Error concerning file: " _
                            & FileNameBox.Text _
                            & ".   " & problem.message())
        End Try
    End If
End Sub
We have singled out FileNotFoundException as the most likely exception, and have produced a specific error message. Other exceptions might occur, but they cannot be neatly classified - so we choose to catch them all in one place, by referring to the class Exception.

 


Section 17.7

Message boxes and dialogs

Sometimes we need to bring the user's attention to a vital decision or piece of information. Merely displaying some text in a label is not enough. VB provides a range of overloaded message box methods to provide configured dialogs. In addition, there are specific dialogs to request file names from the user, which we review later. Here are the message box methods:

MessageBox.Show(message)
MessageBox.Show(message, title)
MessageBox.Show(message, title, buttons)
MessageBox.Show(message, title, buttons, icon)

The arguments are as follows:
  • the message is positioned in the centre of the message box
  • the title argument goes at the top of the message box
  • the buttons argument is a constant specifying any buttons we need. For example we might require yes/no buttons
  • the icon argument specifies a symbol, such as a large exclamation mark or question mark.
The Show method also returns a code which we can examine to find out which button was clicked. There is a set of DialogResult constants which we can use for comparison. Figures 3 and 4 shows some examples, which show a warning message, and a question.
[files3.jpg]
fig3 - Warning with a message box

[files4.jpg]
fig 4 - Question with message box

Here is the code. Note the style of calling the function method within an If, which accomplishes the dual role of displaying the message box and testing the result. When you run the code, you will see that the user cannot return to the form which displayed the message. First, the message box must be closed one way or another. The message box is described as modal.

'warning
MessageBox.Show("The age must be over 18!", _
                "Age is out of range!", _
                MessageBoxButtons.OK, _
                MessageBoxIcon.Exclamation)

'question
If MessageBox.Show("Do you want to buy this?", _
                   "CD Purchase", _
                   MessageBoxButtons.YesNo, _
                   MessageBoxIcon.Question) _
      = DialogResult.Yes Then
    MessageBox.Show("user clicked Yes")
Else
    MessageBox.Show("user clicked No")
End If

SELF-TEST QUESTION 6
Write code to display a message box which asks the question
Is Paris the capital of France?
Display suitable responses to the user's replies.

 


Section 17.8

Using file dialogs

When a user needs to open a file using a word processor or editor, they will make use of file dialog window which allows them to browse directories, and to click on a selected file. Often, an application makes this available via a drop-down file menu at the top left of a window.

In VB, we are provided with the OpenFileDialog and SaveFileDialog classes. Fig 5 shows the appearance of an open dialog. The steps to follow when programming the file dialogs are:

  • we select the dialog from the Dialogs section of the toolbox, and place it on the form. It moves to the component tray, because it does not reside on the form. The first dialog we create will be named OpenFileDialog1.
  • we set its properties as required - at design-time if we know them. One of the most useful properties is its InitialDirectory, which is a string containing a directory path.
  • we display the dialog using its ShowDialog method, which also returns a result to the program. The result indicates how the user closed the dialog e.g. by clicking the Open or the Cancel button. The DialogResult class contains a list of conveniently-named constants we can use.
  • we make use of the FileName property, which provides us with a string containing the name of the selected file.
[files5.jpg]
fig 5 - OpenFileDialog in action

Here is some VB code which creates an OpenFileDialog.

If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
    MessageBox.Show(OpenFileDialog1.FileName)
End If

We set its InitialDirectory property to the c:\ directory.

We then use ShowDialog in an If statement. This compares the number returned from ShowDialog to the constant DialogResult.OK. (Using constants provided by VB is less error-prone than using the numbers themselves.) In this context, 'OK' means that the 'Open' button was clicked. If the user closed the dialog by shutting it down or by cancelling, we take no action. The process of using a SaveFileDialog is virtually identical. The following text editor program shows the dialogs incorporated with a menu containing 'Save', 'Open', and 'Save As' options.

When you have understood the operation of file dialogs, it is recommended that you use them rather than using a text box for file name input. They are slightly more difficult to program, but are much more resistant to file name errors.

 


Section 17.9

Creating a menu

Many applications provide a vast range of facilities, with the consequence that allocating a button to initiate each facility is impractical: too much valuable screen space would be consumed. The menu is one solution to the space problem. It occupies very little space, and its options only become visible when the menu is clicked.

In VB, we can create a menu at the top of a form by selecting MenuStrip from the Menus & Toolbars section of the toolbox, and placing it on a form. (VB then opens the system tray, and places the menu there). A space opens on the top left of the form, where we can type the name of the menu. Once this is done, we are presented with a 'Type Here' prompt, in two positions:

  • we can create a new menu item by typing underneath the existing menu, or
  • we can create a heading for a new list of menu items by typing at the right of the existing menu name.
Figure 6 shows the design-time screen.
[files6.jpg]
fig 6 - Creating a menu at design-time

We have created a menu named 'File', and have added the items 'Open...", "Save", "Save As..." and "Exit". There is a Windows convention of using a file menu at the left of the form, and of using '...' to indicate that further choices will appear. When a menu item has been created, we can change its name at design-time by clicking on it with the right mouse button, and selecting its name via the properties window. Here is the code for a program named Text Editor, and the screenshot is shown in figure 7.

[files7.jpg]
fig 7 - screenshot of the Text Editor program

We renamed the menu items to OpenMenu, SaveMenu, SaveAsMenu, and ExitMenu. VB creates event-handling methods based on these names.

Private currentFile As String = ""   'instance variable

Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, _
                                        ByVal e As System.EventArgs) _
                                        Handles OpenToolStripMenuItem.Click
    Dim inputStream As StreamReader
    OpenFileDialog1.InitialDirectory = "c:\"
    If OpenFileDialog1.ShowDialog() = _
                            DialogResult.OK Then
        currentFile = OpenFileDialog1.FileName
        inputStream = File.OpenText(currentFile)
        TextBox1.Text = inputStream.ReadToEnd()
        inputStream.Close()
    End If
End Sub

Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, _
                                        ByVal e As System.EventArgs) _
                                        Handles SaveToolStripMenuItem.Click
    If currentFile <> "" Then
        Dim outputStream As StreamWriter = _
                           File.CreateText(currentFile)
        outputStream.Write(TextBox1.Text)
        outputStream.Close()
    End If
End Sub

Private Sub SaveAsToolStripMenuItem_Click(ByVal sender As System.Object, _
                                          ByVal e As System.EventArgs) _
                                          Handles SaveAsToolStripMenuItem.Click
    Dim outputStream As StreamWriter
    SaveFileDialog1.InitialDirectory = "c:\"
    If SaveFileDialog1.ShowDialog() = _
        DialogResult.OK Then
        currentFile = SaveFileDialog1.FileName
        outputStream = File.CreateText(currentFile)
        outputStream.Write(TextBox1.Text)
        outputStream.Close()
    End If
End Sub

Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, _
                                        ByVal e As System.EventArgs) _
                                        Handles ExitToolStripMenuItem.Click
    End   'quit immediately
End Sub
The menu usage is quite straightforward, in the sense that VB provides the event method headers - all we need to do is add a text box and some file access. Here are some points on the program.
  • Most of the form area is usable by the text box, as can be seen from its screenshot.
  • The properties of the text box have been set to provide both horizontal and vertical scrollbars. The multi-line property is also set to true.
  • When the user requests the opening of a file, we set the file dialog to start at the C:\ folder.
  • To actually read the file, we make use of the ReadToEnd method of the StreamReader class. This reads all of the file (from the current position) into one string, which will contain end-of-line markers as well as the visible text. We can store this complete string into the text box, by:
    TextBox1.Text = inputStream.ReadToEnd()
    
  • In a similar manner, we can write the whole of the text box to a file with one instruction:
    outputStream.Write(TextBox1.Text)
    
  • The variable currentFile is declared outside the methods as an instance variable, because several methods make use of it.
  • For consistency with other Windows applications, we have provided an exit on our menu. The VB statement End causes the program to terminate immediately.
The text editor program shows the power of VB's components and programming environment:
  • creating the menu was simply a matter of entering the options and amending their names;
  • the file dialogs provide familiar file access;
  • the multi-line text box allows text to be edited. The right mouse button also provides access to the clipboard for cut and paste facilities.

SELF-TEST QUESTION 7
In the Text Editor program, saving the file results in the previous version being overwritten. This is how most editors and word-processors work. Modify its behaviour by providing a dialog which asks the user if the user really wants to do a save.

 


Section 17.10

The Directory class

This class provides facilities to manipulate complete files and directories (folders). It is not concerned with accessing the data within files. You can make use of the Directory class without making use of stream I/O, in the sense that you might wish to manipulate file names rather than the contents of the files. Figure 8 shows the screenshot of a program which displays directories and files within a selected directory, and we examine its code below.
[files8.jpg]
fig 8 - Screenshot of Directory Demo program

Firstly, some terminology. As you know, operating systems provide a hierarchical structure, with a path to a file of the form:

c:\data\exams.txt
This is a Windows-style path, with \ used as a separator. The terminology is that:
  • The whole item is a path
  • the extension is txt
  • the directory path is c:\data
  • the file name in the path is exams.txt
  • if a program refers to a file without providing a directory (e.g. simply exams.txt) then the file is assumed to be in the same directory as the program is stored in and executed from.

Now we will provide details of some selected methods of the Directory class. They are shared: they provide useful methods for operating on strings that contain file paths.

GetFiles

This method operates on a string containing a directory path. It returns an array of strings containing all the file names within the specified directory. The following program (Directory Demo) shows it in action.

Sometimes we might need to check on the type of a file before opening it. Here is an example which checks if a file name ends in .txt. In Windows, capitals can also be used, so we convert the file name to upper-case before testing it. The EndsWith string method is convenient:

Dim fileName As String = "c:\tests\demo.txt"
If fileName.ToUpper().EndsWith(".TXT") Then
    MessageBox.Show("a text file")
End If

GetDirectories

This method operates on a string containing a directory name. It returns an array of strings containing the names of all the directories within the specified directory.
Dim dirs() As String = Directory.GetDirectories("c:\")

The following program shows it in action. Note that this method does not work through a directory tree to the very bottom. It only goes one level deep. Repeated calls of GetFiles are needed to progress deeper.

Here is a program, named Directory Demo, with its screenshot in figure 6. The user can enter a directory name, and the program displays the name of every file and every directory in the chosen directory.

Private Sub Button1_Click(ByVal sender As System.Object _
                  , ByVal e As System.EventArgs) _
                  Handles Button1.Click

    Dim files() As String = _
                   Directory.GetFiles(FileNameBox.Text)
    Dim count As Integer
    For count = 0 To UBound(files)
        FilesBox.AppendText(files(count) & NewLine)
    Next
    'display all directory names
    Dim dirs() As String = _
                  Directory.GetDirectories(FileNameBox.Text)
    For count = 0 To UBound(dirs)
        FolderBox.AppendText(dirs(count) & NewLine)
    Next
End Sub
Once we have filled our arrays, we can use the UBound function to control a loop which looks at each element in turn.

Programming principles

  • Programs use streams to read and write data to files.
  • We use files to preserve data after the run of the program, or for passing data to other programs.

Programming pitfalls

  • Forgetting to put any required importing details at the very top of the code. We used:
    Imports System.IO
    
    

Grammar spot

  • We declare and create file streams by e.g.:
    Dim inputStream As StreamReader = _
                    File.OpenText("c:\myfile.txt")
    
    Dim outputStream As StreamWriter = _
                    File.CreateText("c:\myfile.txt")
    
    
  • We can read a file line-by-line with:
    
    Dim line As String
    line = inputStream.ReadLine()
    While line <> Nothing
        ' process the line...
        line = inputStream.ReadLine()
    End While
    
    
    or we can read the whole file at once with the ReadToEnd Method.
  • We close streams by e.g.:
    
    outStream.Close();
    
    

New language elements

We have introduced these classes:
  • File
  • Directory
  • StreamReader and StreamWriter
  • FileNotFoundException
  • SaveFileDialog and OpenFileDialog

New IDE elements

  • We can place a main menu on a form, and handle menu item clicks via a method that VB generates.
  • We can place file dialogs onto a form. (They move to the component tray.) We can manipulate their properties at design-time and run-time.

SUMMARY

  • Files are opened, then written to (or read from), and finally closed.
  • The Directory class allows you to access the contents of a directory. Its methods allow you to access the names of its sub-directories and its files.

SELF-TEST ANSWERS


ANSWER 1:
It creates a file containing the following text:
*
**
***
 etc

If we omitted to use WriteLine, all the stars would appear on one long line.
ANSWER 2:
When Nothing is returned at the end of the file, its length is displayed, resulting in a value of zero. We need to reverse the order of the two statements within the loop, so that the use of ReadLine is immediately followed by going up to the start of the loop, and the test for end-of-file.


ANSWER 3:
The program loops forever (or at least until the text box becomes full), because there is no ReadLine in the middle of the loop.
ANSWER 4:
We can convert each item to e.g. upper case, as in:
If Trim(words(0)).ToUpper() = studentName.Text.ToUpper() Then
    etc.

ANSWER 5:
A While loop repeats until the complete condition becomes false. Assume that we have two conditions that are initially true, with an Or between them. One condition becoming false does not make the whole condition false, because the other condition is still true.

On the other hand, if we connect the two conditions with And, one condition changing to false makes the overall condition false. It is correct to use And in our search. In our incorrect Or example, if the data is not found, there is no way out of the loop, because both conditions can never become false. The program loops forever.



ANSWER 6:
We provide a question-mark icon, and yes/no buttons, as in:
If MessageBox.Show("Is Paris the capital of France?", _
                   "Quiz", _
                   MessageBoxButtons.YesNo, _
                   MessageBoxIcon.Question) _
          = DialogResult.Yes Then
    MessageBox.Show("Yes - correct!")
Else
    MessageBox.Show("Sorry... wrong.")
End If

ANSWER 7:
We add this code to the save menu event:
If MessageBox.Show("Do you really want to save?", _
                       "Text Editor", _
                       MessageBoxButtons.YesNo, _
                       MessageBoxIcon.Question) _
          = DialogResult.Yes Then
    MessageBox.Show("user clicked Yes")

    'code to save the text box in the file...

End If
 


Section 17.11

EXERCISES

1 Write a program which puts your name and address in a file named address.txt. Use an editor to check that the file has the expected contents.

2 Write a program to count the number of lines in a file. Ensure that it works for an empty file (producing a value of zero).

3 Write a program which examines each line of a file to see if it contains a particular string. Append each of those lines to a multi-line text box, preceded by the file name. Use another text box to hold the string to search for.

4 Write a program which reads two files line-by-line, and compares them for equality. It should display a message stating that the files are either equal or not equal. Obtain the file names by displaying two file dialogs.

5 Write a program which replaces one string by another in each line of a file, writing the new version to another file. Use two text boxes for the 'from' and 'to' strings. You could use The Change method created in Chapter STRINGS.

6 This question involves writing two programs, which assist in extracting parts of files, and inserting the parts into other files. For example, you might use them to insert code examples in an essay, or to insert standard headings at the start of a file.

(a). write a program which reads a file line by line, copying those lines between special markers to an output file. Here is an example of an input file:

Though most blues guitar players
are right-handed, (or left-handed
players who re-strung their guitars,
such as Jimi Hendrix), two left-handed
players have made their mark:
EXTRACTTO:king.txt
Albert King, whose style involves
long bent notes, played slowly.
ENDEXTRACT
EXTRACTTO:rush.txt
Otis Rush, who is a highly-rated
songwriter and singer.
ENDEXTRACT
However, such an approach restricts
the player to simple chord fingerings.
The lines between the first extract are to be copied to the file king.txt, and the second extract is to be copied to rush.txt

(b). Write a program which copies one file line-by-line to another file. Any 'insert' instructions cause the specified file to be inserted in the input file. Here is an example:

List Of Players:
INSERTFROM:king.txt
INSERTFROM:rush.txt

Assume that the files are as above, with no errors in the use of the special insert/extract lines.

7 Write a program which calculates the total number of lines stored in all the text files in a specified folder.

8 Write a program which examines each txt file in a selected folder for lines containing a particular string. Any such lines are to be appended to a multi-line text box, preceded by their file name. Use a text box to allow the user to enter the string to find.

9 Write a program which appends the first 10 lines of every txt file in a selected folder to a multi-line text box, preceded by the file's name. If the file contains less than 10 lines, every line is to be displayed.