The previous section demonstrated how to create a file for use in sequential-access apps. In this section, we discuss how to read (or retrieve) data sequentially from a file. Class ReadSequentialAccessFileForm
(Fig. 17.6) reads records from the file created by the program in Fig. 17.4, then displays the contents of each record. Much of the code in this example is similar to that of Fig. 17.4, so we discuss only the unique aspects of the app.
openButton_Click
When the user clicks Open File, the program calls event handler openButton_Click
(lines 21–66). Line 27 creates an OpenFileDialog
, and line 29 calls its ShowDialog
method to display the Open dialog (see the second screenshot in Fig. 17.6). The behavior and GUI for the Save and Open dialog types are identical, except that Save is replaced by Open. If the user selects a valid filename, lines 49–50 create a FileStream
object and assign 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 or throw a FileNotFoundException
if it does not. (In this example, the FileStream
constructor will not throw a FileNotFoundException
, because the OpenFileDialog
is configured to check that the file exists.) In the last example (Fig. 17.4), we wrote text to the file using a FileStream
object with write-only access. In this example (Fig. 17.6), we specify read-only access to the file by passing constant FileAccess.Read
as the third argument to the FileStream
constructor. This FileStream
object is used to create a StreamReader
object in line 53. The FileStream
object specifies the file from which the StreamReader
object will read text.
Open a file with the FileAccess.Read
file-open mode if its contents should not be modified. This prevents unintentional modification of the contents.
nextButton_Click
When the user clicks the Next Record button, the program calls event handler nextButton_Click
(lines 69–101), 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 74 calls StreamReader
method ReadLine
to read the next record. If an error occurs while reading the file, an IOException
is thrown (caught at line 96), and the user is notified (lines 98–99). Otherwise, line 76 determines whether StreamReader
method ReadLine
re-turned null
(i.e., there’s no more text in the file). If not, line 78 uses string
method Split
to separate the stream of characters that was read from the file into tokens (string
s) that represent the Record
’s properties—the second argument indicates that the tokens are delimited by commas in this file. Line 81 displays the Record
values in the TextBox
es. If ReadLine
returns null
, the program closes the StreamReader
object (line 86), automatically closing the FileStream
object, then notifies the user that there are no more records (lines 92–93).