ProblemYou've designed a custom class. You want to store instances of that class in a file and load them back into instances later, but you don't want the object to open a stream and do all of the necessary reads and writes by itself. SolutionSample code folder: Chapter 12\ReadWriteObjects Add serialization to your class by implementing the ISerializable interface. Serialization is the process of preparing an object's data for transport over a stream (or similar system), and later rebuilding the object from the previously transported content. DiscussionThere are three primary steps needed to make a class serializable:
The following code implements a simple employee class. Serialization support is highlighted: Imports System.Runtime.Serialization ' ----- Mark the entire class with the ' SerializableAttribute attribute. <Serializable( )> _ Public Class Employee ' ----- Mark the class as using ISerializable. Implements ISerializable ' ----- Define the basic members and properties. Public FullName As String Public HireDate As Date Private CurrentSalary As Decimal Public Property Salary( ) As Decimal Get Return CurrentSalary End Get Set(ByVal value As Decimal) If (value >= 0) Then CurrentSalary = value End Set End Property Public Sub New( ) ' ----- Default constructor. This class should ' probably have something more interesting ' or data-preparing, but it's just a ' serialization sample, so no problem. End Sub Public Sub New(ByVal info As SerializationInfo, _ ByVal context As StreamingContext) ' ----- Rebuild a previously serialized object by ' getting the individual member components ' from the serialization store. FullName = info.GetString("FullName") HireDate = info.GetDateTime("HireDate") CurrentSalary = info.GetDecimal("Salary") End Sub Public Sub GetObjectData( _ ByVal info As SerializationInfo, _ ByVal context As StreamingContext) _ Implements ISerializable.GetObjectData ' ----- Serialize the object by adding all the class ' members to the serialization store as ' name-value pairs. info.AddValue("FullName", FullName) info.AddValue("HireDate", HireDate) info.AddValue("Salary", CurrentSalary) End Sub End Class The SerializationInfo object used in both the serialization and deserialization code includes overloads and parallel methods for all the core Visual Basic data types. Once you've prepared your class for serialization, you can include it in a stream using one of the formatters included with the serialization system. The BinaryFormatter class streams out a serializable class in a binary form. The class, located in the System.Runtime.Serialization.Formatters.Binary namespace, connects the serializable object to an open stream. The following code serializes and deserializes an Employee object (as defined in this recipe) to a standard file stream: Imports System.Runtime.Serialization Public Class Form1 Private Sub Button1_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Button1.Click SaveToFile( ) GetFromFile( ) End Sub Private Sub SaveToFile( ) ' ----- Serialize an employee object to a file. Dim newEmp As New Employee Dim outFile As IO. FileStream Dim formatter As New Formatters.Binary.BinaryFormatter ' ----- Build a simple employee record. newEmp.FullName = "John Doe" newEmp.HireDate = #11/7/2005# newEmp.Salary = 10000@ ' ----- Open the data file for storage. outFile = New IO. FileStream("c:\EmpData.dat", _ IO.FileMode.Create) ' ----- Send the employee to the stream through ' a binary serialization formatter. formatter = New Formatters.Binary.BinaryFormatter formatter.Serialize(outFile, newEmp) ' ----- Finished. outFile.Close( ) End Sub Sub GetFromFile( ) ' ----- Build an employee record from storage. Dim oldEmp As Employee = Nothing Dim inFile As IO.FileStream Dim formatter As Formatters.Binary.BinaryFormatter ' ----- Open the file with the stored employee. inFile = New IO.FileStream("c:\EmpData.dat", _ IO.FileMode.Open) ' ----- Deserialize the employee through the binary ' serialization formatter. formatter = New Formatters.Binary.BinaryFormatter oldEmp = CType(formatter.Deserialize(inFile), Employee) inFile.Close( ) ' ----- Prove that the data came back intact. MsgBox("Name: " & oldEmp.FullName & vbCrLf & _ "Hire: " & oldEmp.HireDate.ToString( ) & vbCrLf & _ "Salaray: " & oldEmp.Salary.ToString( )) End Sub End Class The .NET Framework also includes support for nonbinary serialization through distinct XML and SOAP serialization systems. The System.Xml.Serialization.XmlSerializer class provides much of this functionality, although its use differs considerably from the binary formatting presented in this recipe. |