How to serialize and Deserialize your object
This class helps to serialize and deserialize the object
----------------
public static class Serializer
{
public static void Serialize(object Data, string Path)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = null;
try
{
if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(Path)))
{
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(Path));
}
stream = new FileStream
(Path
, FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, Data);
}
finally
{
if (stream != null)
{
stream.Flush();
stream.Close();
}
}
}
public static byte[] Serialize(object Data)
{
//TODO Encryption
IFormatter formatter = new BinaryFormatter();
if (Data == null)
return null;
Stream stream = null;
stream = new MemoryStream();
formatter.Serialize(stream, Data);
byte[] Bytes = new byte[stream.Length];
stream.Position = 0;
stream.Read(Bytes, 0, Bytes.Length);
stream.Flush();
stream.Close();
return Bytes;
}
public static object Deserialize(byte[] Bytes)
{
if (Bytes == null)
return null;
IFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream(Bytes);
object Data = null;
if (stream.Length != 0)
{
stream.Position = 0;
Data = formatter.Deserialize(stream);
}
stream.Close();
return Data;
}
public static object Deserialize(string Path, bool Decrypt)
{
IFormatter formatter = new BinaryFormatter();
if (!System.IO.File.Exists(Path))
return null;
FileStream stream = null;
try
{
stream = new FileStream
(Path
, FileMode.Open, FileAccess.Read, FileShare.None);
object Data = null;
if (stream.Length != 0)
{
stream.Position = 0;
Data = formatter.Deserialize(stream);
}
return Data;
}
finally
{
if (stream != null)
{
stream.Close();
}
}
}
}
Hello
Nice piece of code
Thanks for sharing your knowledge with us.
I hope to see more good code from your side
This code will help lots of guys
Thanks to you
Regards,
Kapil