Monday, September 03, 2007

convert an object in to byte array or byte array to object

I was looking for a sample code snippet to convert an object in to byte array. finally i had to do it on my own.


public byte[] objectToByte(Object obj )
{
MemoryStream fs = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, obj);
return fs.ToArray() ;
}
catch (SerializationException e )
{
return null;
}
finally
{
fs.Close();
}
}




public object ByteArrayToObject(Byte[] Buffer )
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream(Buffer);
try
{
return formatter.Deserialize(stream);
}
catch
{
return null;
}
}

No comments: