Serialization and deserialization

Serialization is the process of converting an object into a stream of data so that it can be easily transmittable over the network


Serialization is the process of converting an object into a stream of data so that it can be easily transmittable over the network

if you want to store an object (or multiple objects) in a file for later retrieval,
you store the output of serialization. The next time you want to read the objects, you
call the deserialization methods

To serialize an object

* Create an object Stream
* Create a BinaryFormatter
* Call the BinaryFormatter.Serialize method to serialize

string data = "This must be stored in a file or folder";
FileStream fs = new FileStream("Serialization.Data", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, data);

If you open the file in a notepad you can notice the contents of your file surrounded by binary numbers


Deserialization is the process of converting a previously serialized sequence of bytes into an object

To deserialize

* Create an object Stream to read a serialized output
* Create a BinaryFormatter object
* Create an object to store a Deserialized data
* USE the BinaryFormatter.Deserialize method to deserialize the object

filestream fs = new FileStream("Serialize.Data", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
string data = "";
data = (string)bf.Deserialize(fs);


Author: kewal16 Feb 2011 Member Level: Silver   Points : 1

public class myTestClass
public string myString = "Hello World";
public int myInt = 1234;
public string[] myArray = new string[4];
private int myPrivateInt = 4321;

public string myMethod()
return "Hello World";

class Program
static void Main()
// create new object and populate test data
myTestClass test = new myTestClass();
test.myArray[0] = "qwerty";
test.myArray[1] = "asdfgh";
test.myArray[2] = "zxcvbn";
test.myArray[3] = "123456";

// these lines do the actual serialization
XmlSerializer mySerializer = new XmlSerializer(typeof(myTestClass));
StreamWriter myWriter = new StreamWriter("c:/myTestClass.xml");
//serialize method which takes stream writter and class object to be serialized
mySerializer.Serialize(myWriter, test);


static void Main()
myTestClass test;

XmlSerializer mySerializer = new XmlSerializer(typeof(myTestClass));
FileStream myFileStream = new FileStream("c:/mtTestClass.xml",FileMode.Open);

test = (myTestClass)mySerializer.Deserialize(myFileStream);

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: