When we create objects in .NET Framework, they reside in memory as long as our program runs and .NET Framework Runtime takes care of all the details of creating and destroying objects in Memory. The contents of the object are available temporarily to your program, and if you want to store these contents you need to do little more than just loading objects and using them.
Many applications need to store and transfer contents of the object. The process of storing object data in different formats so that they can easily be transferred or reused later is called Serialization. Once object is stored it can easily be retrieved and constructed in the memory. This process is called Deserialization.
.NET Framework 2.0 provides many serialization techniques to the developers. These techniques include saving object into a binary format, SOAP format or even as XML documents. In this tutorial I will show you how to serialize and deserialize objects in a binary format using .NET Framework classes.
In .NET Framework, serialization is implemented in the System.Runtime.Serialization namespace. For binary serialization we also need to import System.Runtime.Serialization.Formatters.Binary namespace.
Following code serializes .NET string object by using BinaryFormatter class.
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace BinarySerializationTest
{
class Program
{
static void Main(string[] args)
{
// Serialization of String Object
String writeData = "Microsoft .NET Framework 2.0";
FileStream writeStream = new FileStream("C:\\StringObject.data", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(writeStream, writeData);
writeStream.Close();
// Deserialization of String Object
FileStream readStream = new FileStream("C:\\StringObject.data", FileMode.Open);
String readData = (String) formatter.Deserialize(readStream);
readStream.Close();
Console.WriteLine(readData);
Console.Read();
}
}
}
The line
“Formatter1.Serialize(writeStream, writeData);”
has to be changed in
“formatter.Serialize(writeStream, writeData);”
Greetings Arno