C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » .NET Framework »

Serialization


Posted Date: 19 Jan 2007    Resource Type: Articles    Category: .NET Framework
Author: E. Murali ShankarMember Level: Bronze    
Rating: 1 out of 5Points: 6



Serialization :

Many applications need to store or transfer data stored in objects. To make these tasks
as simple as possible, the .NET Framework includes several serialization techniques.
These techniques convert objects into binary, Simple Object Access Protocol (SOAP),
or XML documents that can be easily stored, transferred, and retrieved. This post
discusses how to implement serialization using the tools built into the .NET Framework
and how to implement serialization to meet custom requirements.

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.

How to Serialize an Object
At a high level, the steps for serializing an object are as follows:
1. Create a stream object to hold the serialized output.
2. Create a BinaryFormatter object (located in System.Runtime.Serialization.Formatters
.Binary).
3. Call the BinaryFormatter.Serialize method to serialize the object, and output the
result to the stream.
At the development level, serialization can be implemented with very little code. The following
console application—which requires the System.IO, System.Runtime.Serialization,
and System.Runtime.Serialization.Formatters.Binary namespaces—demonstrates this:
' 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();
If you run the application and open the SerializedString.Data file in Notepad, you’ll
see the contents of the string you stored surrounded by binary information (which
appears as garbage in Notepad). The .NET Framework stored the string as ASCII text and then added a few more binary bytes before and after the
text to describe the data for the deserializer.
If you just needed to store a single string in a file, you wouldn’t need to use serialization—
you could simply write the string directly to a text file. Serialization becomes
useful when storing more complex information, such as the current date and time. As
the following code sample demonstrates, serializing complex objects is as simple as
serializing a string:
' VB
' Create file to save the data to
Dim fs As FileStream = New FileStream("SerializedDate.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, System.DateTime.Now)
' Close the file
fs.Close()
// C#
// Create file to save the data to
FileStream fs = new FileStream("SerializedDate.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, System.DateTime.Now);
// Close the file
fs.Close();

How to Deserialize an Object
Deserializing an object allows you to create a new object based on stored data. Essentially,
deserializing restores a saved object. At a high level, the steps for deserializing an
object are as follows:
1. Create a stream object to read the serialized output.
2. Create a BinaryFormatter object.
3. Create a new object to store the deserialized data.
4. Call the BinaryFormatter.Deserialize method to deserialize the object, and cast it
to the correct type.
At the code level, the steps for deserializing an object are easy to implement. The following
console application—which requires the System.IO, System.Runtime.Serialization,
and System.Runtime.Serialization.Formatters.Binary namespaces—demonstrates how to
read and display the serialized string data saved in an earlier example:
' VB
' Open file to read the data from
Dim fs As FileStream = New FileStream("SerializedString.Data", _
FileMode.Open)
' Create a BinaryFormatter object to perform the deserialization
Dim bf As BinaryFormatter = New BinaryFormatter
' Create the object to store the deserialized data
Dim data As String = ""
' Use the BinaryFormatter object to deserialize the data from the file
data = CType(bf.Deserialize(fs),String)
' Close the file
fs.Close
' Display the deserialized string
Console.WriteLine(data)
// C#
// Open file to read the data from
FileStream fs = new FileStream("SerializedString.Data", FileMode.Open);
// Create a BinaryFormatter object to perform the deserialization
BinaryFormatter bf = new BinaryFormatter();
// Create the object to store the deserialized data
string data = "";
// Use the BinaryFormatter object to deserialize the data from the file
data = (string) bf.Deserialize(fs);
// Close the file
fs.Close();
// Display the deserialized string
Console.WriteLine(data);

Deserializing a more complex object, such as DateTime, works exactly the same. The
following code sample displays the day of the week and the time stored by a previous
code sample:
' VB
' Open file to read the data from
Dim fs As FileStream = New FileStream("SerializedDate.Data", FileMode.Open)
' Create a BinaryFormatter object to perform the deserialization
Dim bf As BinaryFormatter = New BinaryFormatter
' Create the object to store the deserialized data
Dim previousTime As DateTime = New DateTime
' Use the BinaryFormatter object to deserialize the data from the file
previousTime = CType(bf.Deserialize(fs),DateTime)
' Close the file
fs.Close
' Display the deserialized time
Console.WriteLine(("Day: " _
+ (previousTime.DayOfWeek + (", Time: " _
+ previousTime.TimeOfDay.ToString))))
// C#
// Open file to read the data from
FileStream fs = new FileStream("SerializedDate.Data", FileMode.Open);
// Create a BinaryFormatter object to perform the deserialization
BinaryFormatter bf = new BinaryFormatter();
// Create the object to store the deserialized data
DateTime previousTime = new DateTime();
// Use the BinaryFormatter object to deserialize the data from the file
previousTime = (DateTime) bf.Deserialize(fs);
// Close the file
fs.Close();
// Display the deserialized time
Console.WriteLine("Day: " + previousTime.DayOfWeek + ", _
Time: " + previousTime.TimeOfDay.ToString());

I will continue explaining how to serialize and deserialize objects in my next post.






Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Making your class clonable.
Previous Resource: Visual Studio 2005 SP1 - Features - What is there in it?
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use