Serialization Sample Code


Sample code on Serialization.

To compile:

csc /r:System.dll /r:System.Web.dll SGSerialization.cs

To run:

SGSerialization.exe

Source Code:

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web.Util;
namespace SG
{
public class SGSerialization
{
private int x;
public SGSerialization()
{
x = 4;
}
public int X
{
get { return x; }
set { x = value; }
}
public static void Main()
{
SGSerialization objA =
new SGSerialization();
Console.WriteLine("Saving objA to serialised format as x.data");
saveProfile("C:\\x.data",objA);
Console.WriteLine("Loading serialized x.data");
SGSerialization objB = (SGSerialization) loadProfile("C:\\x.data");
Console.WriteLine("The value of x from x.data = "+objB.X);
}
public static void saveProfile(String filePath, Object obj)
{
FileStream s =
new FileStream(filePath, FileMode.Create, FileAccess.Write);
BinaryFormatter b =
new BinaryFormatter();
b.Serialize(s, obj);
s.Close();
}
public static Object loadProfile(String filePath)
{
FileStream s =
new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryFormatter b =
new BinaryFormatter();
object savedObject = b.Deserialize(s);
return (Object) savedObject;
}
}
}

Up Next
    Ebook Download
    View all
    Learn
    View all