Monday 2 January 2012

Serializing Objects

Serializing Objects
When you create an object in a .NET Framework application, you probably never
think about how the data is stored in memory. You shouldn’t have to—the .NET
Framework takes care of that for you. However, if you want to store the contents of an
object to a file, send an object to another process, or transmit an object across the network,
you do have to think about how the object is represented because you will need
to convert it to a different format. This conversion is called serialization.

What Is Serialization?
Serialization, as implemented in the System.Runtime.Serialization namespace, is the
process of serializing and deserializing objects so that they can be stored or transferred
and then later re-created. Serializing is the process of converting an object into
a linear sequence of bytes that can be stored or transferred. Deserializing is the process
of converting a previously serialized sequence of bytes into an object.

' VB
Dim data As String = "This must be stored in a file."
' Create file to save the data to
Dim fs As FileStream = New FileStream("SerializedString.Data", _
FileMode.Create)
' Create a BinaryFormatter object to perform the serialization
Dim bf As BinaryFormatter = New BinaryFormatter
' Use the BinaryFormatter object to serialize the data to the file
bf.Serialize(fs, data)
' Close the file
fs.Close



// C#
string data = "This must be stored in a file.";
// Create file to save the data to
FileStream fs = new FileStream("SerializedString.Data", FileMode.Create);
// Create a BinaryFormatter object to perform the serialization
BinaryFormatter bf = new BinaryFormatter();
// Use the BinaryFormatter object to serialize the data to the file
bf.Serialize(fs, data);
// Close the file
fs.Close();

No comments:

Post a Comment