DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Convert Object To Byte Array And Viceversa (serialization)
// Convert an object to a byte array
private byte[] ObjectToByteArray(Object obj)
{
if(obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
// Convert a byte array to an Object
private Object ByteArrayToObject(byte[] arrBytes)
{
MemoryStream memStream = new MemoryStream();
BinaryFormatter binForm = new BinaryFormatter();
memStream.Write(arrBytes, 0, arrBytes.Length);
memStream.Seek(0, SeekOrigin.Begin);
Object obj = (Object) binForm.Deserialize(memStream);
return obj;
}
p.s. for custom classes add [Serializable] attribute to enable serialization






Comments
Snippets Manager replied on Mon, 2010/07/12 - 11:37am
Snippets Manager replied on Mon, 2011/07/11 - 12:45pm
Snippets Manager replied on Wed, 2011/05/11 - 11:44am
Snippets Manager replied on Fri, 2011/01/28 - 4:35pm
Snippets Manager replied on Tue, 2010/11/02 - 5:39am
Snippets Manager replied on Fri, 2009/12/04 - 1:15pm