What is
Serialization?
Serialization is the process of bringing an object into a form that it can be written on stream. It's the process of converting the object into a form so that it can be stored on a file, database, or memory; or, it can be transferred across the network. Its main purpose is to save the state of the object so that it can be recreated when needed.
Serialization is the process of bringing an object into a form that it can be written on stream. It's the process of converting the object into a form so that it can be stored on a file, database, or memory; or, it can be transferred across the network. Its main purpose is to save the state of the object so that it can be recreated when needed.
What is
Deserialization?
As the name suggests, deserialization
is the reverse process of serialization. It is the process of getting back the
serialized object so that it can be loaded into memory. It resurrects the state
of the object by setting properties, fields etc.
Warning
Binary serialization can be dangerous. Never deserialize data from an untrusted source and never round-trip serialized data to systems not under your control.
using System;
using System.IO;
using System.Runtime.Serialization;
using
System.Runtime.Serialization.Formatters.Binary;
namespace HashTable_and_Dictionary
{
class Program
{
static void Main(string[] args)
{
BinarySerialize binarySerialize = new BinarySerialize();
binarySerialize.BinarySerilizeWrite();
binarySerialize.BinarySerilizeRead();
}
}
[Serializable]
public class MyObject
{
public int n1 = 0;
public int n2 = 1;
public string str = null;
}
class BinarySerialize
{
public void BinarySerilizeWrite()
{
MyObject Obj = new MyObject();
Obj.n1 = 1;
Obj.n2 = 2;
Obj.str = "Welcome";
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("C:\\Test\\Binary.bin", FileMode.Create,
FileAccess.Write, FileShare.None);
formatter.Serialize(stream, Obj);
stream.Close();
}
public void BinarySerilizeRead()
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("C:\\Test\\Binary.bin", FileMode.Open,
FileAccess.Read, FileShare.Read);
MyObject obj =
(MyObject)formatter.Deserialize(stream);
stream.Close();
Console.WriteLine("n1: {0}", obj.n1);
Console.WriteLine("n2: {0}", obj.n2);
Console.WriteLine("str: {0}", obj.str);
Console.ReadLine();
}
}
}
No comments:
Post a Comment