18.6. Reading Data from a Sequential-Access Text FileThe preceding section demonstrated how to create a file for use in sequential-access applications. In this section, we discuss how to read (or retrieve) data sequentially from a file. Class FrmReadSequentialAccessFile (Fig. 18.11) reads records from the file created in Fig. 18.9, then displays the contents of each record. Much of the code in this example is similar to that in Fig. 18.9, so we discuss only the unique aspects of the application. Figure 18.11. Reading sequential-access files.
When the user clicks the Open File button, the program calls event handler btnOpen_Click (lines 1140). Line 14 creates an OpenFileDialog, and line 15 calls its ShowDialog method to display the Open dialog (see the second screenshot in Fig. 18.11). The behavior and GUI for the Save and Open dialog types are identical, except that Save is replaced by Open. If the user inputs a valid file name, line 32 creates a FileStream object and assigns it to reference input. We pass constant FileMode.Open as the second argument to the FileStream constructor to indicate that the FileStream should open the file if it exists and throw a FileNotFoundException if the file does not exist. In the last example (Fig. 18.9), we wrote text to the file using a FileStream object with write-only access. In this example (Fig. 18.11), we specify read-only access to the file by passing constant FileAccess.Read as the third argument to the FileStream constructor (line 32). This FileStream object is used to create a StreamReader object in line 35. The FileStream object specifies the file from which the StreamReader object will read text. Error-Prevention Tip 18.1
When the user clicks the Next Record button, the program calls event handler btnNext_Click (lines 4377), which reads the next record from the user-specified file. (The user must click Next Record after opening the file to view the first record.) Line 48 calls StreamReader method ReadLine to read the next record. If an error occurs while reading the file, an IOException is thrown (caught at line 73), and the user is notified (line 7475). Otherwise, line 53 determines whether StreamReader method ReadLine returned Nothing (i.e., there is no more text in the file). If not, line 54 uses method Split of class String to separate the stream of characters that was read from the file into strings that represent the Record's properties. Recall that the fields of each record are separated by commas. These properties are then stored by constructing a Record object using the properties as arguments (lines 5658). Line 61 displays the Record values in the TextBoxes by invoking method SetTextBoxes, which was inherited from class FrmBankUI. If ReadLine returns Nothing, the program closes both the StreamReader object (line 63) and the FileStream object (line 64), then notifies the user that there are no more records (lines 7071). |