Skip to content

Instantly share code, notes, and snippets.

@LorenzGit
Last active July 11, 2023 01:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LorenzGit/2cd665b6b588a8bb75c1a53f4d6b240a to your computer and use it in GitHub Desktop.
Save LorenzGit/2cd665b6b588a8bb75c1a53f4d6b240a to your computer and use it in GitHub Desktop.
Convert an object to byte[] and back using BinaryFormatter
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class Program
{
[Serializable]
class MyObj{
public string name = "hello world";
public int id = 1;
public string[] strings = new string[]{"apple", "orange", "banana"};
public override string ToString()
{
string s = "";
s += name+"|";
s += id+"|";
foreach(var st in strings){s+=st+"|";}
return s;
}
}
public static void Main()
{
////USING BINARY FORMATTER
byte[] bytes = ObjectToByteArray( new MyObj() );
Console.WriteLine( Convert.ToBase64String(bytes) );
MyObj myObj = ByteArrayToObject(bytes) as MyObj;
Console.WriteLine(myObj);
/////////////////////
}
////USING BINARY FORMATTER
// Convert an object to a byte array
public static byte[] ObjectToByteArray(Object obj)
{
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
// Convert a byte array to an Object
public static Object ByteArrayToObject(byte[] arrBytes)
{
using (var memStream = new MemoryStream())
{
var binForm = new BinaryFormatter();
memStream.Write(arrBytes, 0, arrBytes.Length);
memStream.Seek(0, SeekOrigin.Begin);
var obj = binForm.Deserialize(memStream);
return obj;
}
}
///////////////
}
@Blixtdraken
Copy link

bagel

@oofman124
Copy link

bagel

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment