Serailization in .NET
Serialization:
Serialization is the process of saving the state of an object in a persistent storage media in the form of linear stream of bytes. The object can be stored to a file, a database or even in the memory. Serialization in .NET is provided by the System.Runtime.Serialization namespace.
In order for a class to be serializable, it must have the attribute SerializableAttribute set
and all its members must also be serializable, except if they are ignored with the attribute NonSerializedAttribute. However, the private and public members of a class are always serialized by default. The SerializationAttribute is only used for the binary serialization.
[Serializable]
public class Student
{
private int StudentID;
public string StudentName;
public void dispaly()
{
Console.WriteLine("Student Name "+ StudentName);
}
}
Binary Serialization:
In Binary serialization the entire object state is saved. Both public and private members states are saved.
//The following way Student object is serialized
public void BinarySerialize(string filename, Student Stud)
{
FileStream fileStreamObject;
try
{
fileStreamObject = new FileStream(filename, FileMode.Create);
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(fileStreamObject, Stud);
}
finally
{
fileStreamObject.Close();
}
}
//The following way Deserialize the Student Object
public static object BinaryDeserialize(string filename)
{
FileStream fileStreamObject;
try
{
fileStreamObject = new FileStream(filename, FileMode.Open);
BinaryFormatter binaryFormatter = new BinaryFormatter();
return (binaryFormatter.Deserialize(fileStreamObject));
}
finally
{
fileStreamObject.Close();
}
}
Serialization is used to transportation of an object through a network.
Labels:
.NET,
C#,
Serilization
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment