Serialization & DeSerialization

Namespaces to be used:
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;



namespace ConsoleApplication9
{
[Serializable]
public class myclass
{
public int myint1;
public int myint2;
public string mystring;
}
class Program
{
static void Main(string[] args)
{
myclass mc = new myclass();
mc.myint1 = 200;
mc.myint2 = 900;
mc.mystring = "hello .net world...";
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("demo.bin", FileMode.Create, FileAccess.Write);
formatter.Serialize(stream, mc);
stream.Close();
Console.WriteLine("serialized...");



}
}
}



Explanation:

The objects r serialized using serializable attribute.

The above snippet is used to serialize the object (mc) of class my class in a file demo. Bin

DeSerialization

The following snippet is used to retrieve the data from serialized object.

namespace ConsoleApplication9
{
[Serializable]
public class myclass
{
public int myint1;
public int myint2;
public string mystring;
}
class Program
{
static void Main(string[] args)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("demo.bin", FileMode.OpenOrCreate, FileAccess.Read);
myclass mc = (myclass)formatter.Deserialize(stream);
stream.Close();
Console.WriteLine(mc.mystring);
Console.WriteLine(mc.myint1);
Console.WriteLine(mc.myint2);



}
}
}




Explanation:

The above snippet is deserialize the serialized objects


Comments

No responses found. Be the first to comment...


  • 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:
    Email: