17.4 Reading Data from a Sequential-Access Text File

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.

Fig. 17.6 Reading a sequential-access file.

Alternate View

  1    // Fig. 17.6: ReadSequentialAccessFileForm.cs
  2    // Reading a sequential-access file.
  3    using System;
  4    using System.Windows.Forms;
  5    using System.IO;
  6    using BankLibrary;
  7
  8    namespace ReadSequentialAccessFile
  9    {
 10       public partial class ReadSequentialAccessFileForm : BankUIForm
 11       {
 12          private StreamReader fileReader; // reads data from a text file
 13
 14          // parameterless constructor
 15          public ReadSequentialAccessFileForm()
 16          {
 17             InitializeComponent();
 18          }
 19
 20          // invoked when user clicks the Open button
 21          private void openButton_Click(object sender, EventArgs e)
 22          {
 23             // create and show dialog box enabling user to open file
 24             DialogResult result; // result of OpenFileDialog
 25             string fileName; // name of file containing data
 26         
 27             using (OpenFileDialog fileChooser = new OpenFileDialog())
 28             {
 29                result = fileChooser.ShowDialog();
 30                fileName = fileChooser.FileName; // get specified name
 31             }
 32         
 33             // ensure that user clicked "OK"
 34             if (result == DialogResult.OK)
 35             {
 36                ClearTextBoxes();
 37         
 38                // show error if user specified invalid file
 39                if (string.IsNullOrEmpty(fileName))
 40                {
 41                   MessageBox.Show("Invalid File Name", "Error",
 42                      MessageBoxButtons.OK, MessageBoxIcon.Error);
 43                }
 44                else
 45                {
 46                   try
 47                   {
 48                      // create FileStream to obtain read access to file
 49                      FileStream input = new FileStream(            
 50                          fileName, FileMode.Open, FileAccess.Read);
 51               
 52                      // set file from where data is read
 53                      fileReader = new StreamReader(input);
 54               
 55                      openButton.Enabled = false; // disable Open File button
 56                      nextButton.Enabled = true; // enable Next Record button
 57                    }
 58                    catch (IOException)
 59                    {
 60                       MessageBox.Show("Error reading from file",
 61                          "File Error", MessageBoxButtons.OK,
 62                          MessageBoxIcon.Error);
 63                    }
 64                }
 65             }
 66          }
 67         
 68          // invoked when user clicks Next button
 69          private void nextButton_Click(object sender, EventArgs e)
 70          {
 71             try
 72             {
 73                // get next record available in file
 74                var inputRecord = fileReader.ReadLine();
 75            
 76                if (inputRecord != null)
 77                {
 78                   string[] inputFields = inputRecord.Split(',');
 79            
 80                    // copy string-array values to TextBox values
 81                    SetTextBoxValues(inputFields);
 82                }
 83                else
 84                {
 85                   // close StreamReader and underlying file
 86                   fileReader.Close();
 87                   openButton.Enabled = true; // enable Open File button
 88                   nextButton.Enabled = false; // disable Next Record button
 89                   ClearTextBoxes();
 90             
 91                    // notify user if no records in file
 92                    MessageBox.Show("No more records in file", string.Empty,
 93                       MessageBoxButtons.OK, MessageBoxIcon.Information);
 94                 }
 95              }
 96              catch (IOException)
 97              {
 98                 MessageBox.Show("Error Reading from File", "Error",
 99                    MessageBoxButtons.OK, MessageBoxIcon.Error);
100            }
101         }
102      }
103   }

Method 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.

Error-Prevention Tip 17.1

Open a file with the FileAccess.Read file-open mode if its contents should not be modified. This prevents unintentional modification of the contents.

Method 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 (strings) 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 TextBoxes. 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).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset