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