Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Binary Files ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT

Similar presentations


Presentation on theme: "1 Binary Files ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT"— Presentation transcript:

1 1 Binary Files ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT Email: mmunlin@gmail.com

2 2 OBJECTIVES  To use classes FileStream and BinaryFormatter to read objects from and write objects to files.

3 3 19.8 Serialization 19.9 Creating a Sequential-Access File Using Object Serialization 19.10 Reading and Deserializing Data from a Binary File

4 4 19.8 Serialization Sometimes it is easier to read or write entire objects than to read and write individual fields. C# provides such a mechanism, called object serialization. A serialized object is an object represented as a sequence of bytes that includes the object’s data, its type and the types of data stored in the object. After a serialized object has been written to a file, it can be read from the file and deserialized.

5 5 19.8 Serialization (Cont.) Class BinaryFormatter enables entire objects to be written to or read from a stream. BinaryFormatter method Serialize writes an object’s representation to a file. BinaryFormatter method Deserialize reads this representation from a file and reconstructs the original object. Both methods throw a SerializationException if an error occurs during serialization or deserialization.

6 6 Defining the S erializable Class Account Class Account is marked with the [Serializable] attribute, which indicates that Account objects can be serialized. Outline Account.cs [Serializable] public class Account { public string First { get; set; } public string Number { get; set; } public string Last { get; set; } private decimal balance; // instance variable that stores the balance public static int totalAcc = 0; public int CurAcc { get; set; } public Account() { totalAcc++; Balance = 500.00M; // set balance using property } // end Account constructor

7 7 19.9 Creating a Sequential-Access File Using Object Serialization (Cont.) The classes for objects that we wish to serialize must include this attribute in their declarations or must implement interface ISerializable. In a serializable class, you must ensure that every instance variable of the class is also serializable. All simple-type variables and string s are serializable. For variables of reference types, their types must be serializable. By default, array objects are serializable. However, if the array contains references to other objects, those objects may or may not be serializable.

8 8 Using a Serialization Stream to Create an Output File Now let’s create a sequential-access file with serialization (Fig. 19.14). Outline CreateFileForm.cs (1 of 11 ) Create a BinaryFormatter for writing serialized objects. using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization; // SerializationException namespace BinFile { public partial class Form1 : Form { List myAccList; int numAcc = 0; int curAcc = 0; // object for serializing Records in binary format private BinaryFormatter formatter = new BinaryFormatter(); private BinaryFormatter reader = new BinaryFormatter(); private FileStream output; // stream for writing to a file private FileStream input; // stream for reading from a file Create the BinaryFormatter that will be used to read objects.

9 9 Outline try { // open file with write access output = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write); // write Record to file, fields separated by commas // foreach (var acc in myAccList) // write Record to FileStream ( serialize object ) formatter.Serialize(output, myAccList); output.Close(); }// end try // handle exception if there is a problem opening the file catch (SerializationException) { // notify user if file does not exist MessageBox.Show("Error opening file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } // end catch Call method Serialize to write the entire list of Account object to the output file.

10 10 Write to Binary File

11 11 Binary File

12 12 Outline Common Programming Error 19.2 It is a logic error to open an existing file for output when the user wishes to preserve the file. The original file’s contents will be lost. Method Serialize takes the FileStream object as the first argument so that the BinaryFormatter can write its second argument to the correct file. Remember that we are now using binary files, which are not human readable.

13 13 19.10 Reading and Deserializing Data from a Binary File try { // create FileStream to obtain read access to file input = new FileStream( fileName, FileMode.Open, FileAccess.Read); // get next RecordSerializable available in file myAccList = (List )reader.Deserialize(input); Account.totalAcc = myAccList.Count; numAcc = Account.totalAcc; curAcc = 0; PopulateAcc(); input.Close(); // close FileStream if no Records in file }// end try // handle exception if there is a problem opening the file catch (SerializationException) { input.Close(); // close FileStream if no Records in file // notify user if no Records in file MessageBox.Show("No more records in file", string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information); } // end catch Open the file for input by creating a FileStream object. We use method Deserialize (of the BinaryFormatter ) to read the data.

14 14 Outline 14 Read from Binary File Deserialize returns a reference of type object. If an error occurs during deserialization, a SerializationException is thrown.

15 Assignment Implement DeleteAccount( ) to delete the current or selected account. Add telephone number to the class Account and implement method Search( ) to search the account using the phone number.


Download ppt "1 Binary Files ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT"

Similar presentations


Ads by Google