17.8 Reading and Deserializing Data from a Binary File

The preceding section showed how to create a sequential-access file using object serialization. In this section, we discuss how to read serialized objects sequentially from a file. Figure 17.10 reads and displays the contents of the clients.ser file created by the program in Fig. 17.9. The sample screen captures are identical to those of Fig. 17.6, so they are not shown here. Line 15 creates the BinaryFormatter that will be used to read objects. The program opens the file for input by creating a FileStream object (lines 51–52). The name of the file to open is specified as the first argument to the FileStream constructor.

The program reads objects from a file in event handler nextButton_Click (lines 61–93). We use method Deserialize (of the BinaryFormatter created in line 15) to read the data (lines 67–68). Note that we cast the result of Deserialize to type RecordSerializable (line 67)—Deserialize returns a reference of type object, so we must perform this cast to access properties that belong to class RecordSerializable. If an error occurs during deserialization or the end of the file is reached, a SerializationException is thrown, and the FileStream object is closed (line 83).

Fig. 17.10 Reading a sequential-access file using deserialization.

Alternate View

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

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