Skip to content

Instantly share code, notes, and snippets.

@Immerseit
Created December 14, 2012 11:07
Show Gist options
  • Save Immerseit/4284683 to your computer and use it in GitHub Desktop.
Save Immerseit/4284683 to your computer and use it in GitHub Desktop.
Sample of a normal Serialize / Deserialize .NET objects to Byte array (and back)
//
// Convert a object to byte array
//
ObjectType _theObject; // Populates from somewhere
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
formatter.Serialize(ms, _theObject);
byte[] bytes = ms.ToArray();
FileStream fs = new FileStream("dummy.bin", FileMode.Create);
fs.Write(bytes, 0, bytes.Length);
fs.Close();
//
// Convert a stream to object
//
byte[] bytes; // Populates from somewhere. I.e. File.ReadAllBytes
MemoryStream ms = new MemoryStream(bytes);
ms.Seek(0, 0);
BinaryFormatter bf = new BinaryFormatter();
ObjectType d = (ObjectType)bf.Deserialize(ms);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment