Thursday, December 25, 2008

How to do Serialization in .NET ?

To save an object or to support object persistence, Serialization helps in more.

Say suppose we have a user defined class and when we create object for that class it gets created in heap memory which is volatile or temporary.
So to save the object content we can Serialize the content which is in memory and save it into a text file.
So after de Serializing the content from text file to object type we get the object into hand to perform operations.

.NET Frame work has
System.Runtime.Serialization;
System.Runtime.Serialization.Formatters;
System.Runtime.Serialization.Formatters.Soap;
libraries to support Serialization and De Serialization.


Ex :-

Serialization

public int SaveUserDetails(UserInfo objUserInfo,string strFilePath)
{
FileStream objStream = null;
IFormatter formatter = null;
try
{

objStream = new FileStream(strFilePath, FileMode.Create, FileAccess.Write, FileShare.Write);
formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize(objStream, objUserInfo);
}
catch (Exception exp)
{
throw exp;
}
finally
{
if (objStream != null)
{
objStream.Close();
}
}
}

De Serialization


public UserInfo GetUserDetails(string strFilePath)
{
FileStream objStream = null;
IFormatter formatter = null;
try
{
if (!File.Exists(strFilePath))
{
return null;
}
objStream = new FileStream(strFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
return (UserInfo)formatter.Deserialize(objStream);
}
catch (Exception exp)
{
throw exp;
}
finally
{
if (objStream != null)
{
objStream.Close();
}
}
}

No comments: