Created
February 10, 2020 13:36
-
-
Save CapitanLiteral/9aee0a552ab57bd205e4938246b38906 to your computer and use it in GitHub Desktop.
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
public static class BinaryFormatterWrapper | |
{ | |
private static BinaryFormatter BinaryFormatter => binaryFormatter ?? (binaryFormatter = new BinaryFormatter()); | |
private static BinaryFormatter binaryFormatter; | |
public static byte[] SerializeToByteArray(this object obj) | |
{ | |
using (MemoryStream memoryStream = new MemoryStream()) | |
{ | |
BinaryFormatter.Serialize(memoryStream, obj); | |
return memoryStream.ToArray(); | |
} | |
} | |
public static T DeserializeFromByteArray<T>(this byte[] byteArray) where T : class | |
{ | |
using (MemoryStream memoryStream = new MemoryStream()) | |
{ | |
memoryStream.Write(byteArray, 0, byteArray.Length); | |
memoryStream.Seek(0, SeekOrigin.Begin); | |
T obj = (T)BinaryFormatter.Deserialize(memoryStream); | |
return obj; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment