Last active
July 11, 2023 01:27
-
-
Save LorenzGit/2cd665b6b588a8bb75c1a53f4d6b240a to your computer and use it in GitHub Desktop.
Convert an object to byte[] and back using BinaryFormatter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
/////////////// | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
bagel