Last active
October 1, 2015 06:24
-
-
Save allyusd/fc9850ebd3f1219e6df1 to your computer and use it in GitHub Desktop.
C# Serialization
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
[Serializable] | |
/// <summary> Book Class </summary> | |
internal class Book | |
{ | |
/// <summary> Book Name </summary> | |
public string Name { get; set; } | |
/// <summary> Book ID </summary> | |
public int Id { get; set; } | |
/// <summary> Book PublishDate </summary> | |
public DateTime PublishDate { get; set; } | |
/// <summary> Book RawData </summary> | |
public byte[] RawData { get; set; } | |
} |
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 void Main(string[] args) | |
{ | |
Book book = new Book(); | |
book.Name = "Test Book"; | |
book.Id = 12345; | |
book.PublishDate = DateTime.Now; | |
book.RawData = new byte[] {1, 2, 3}; | |
byte[] data = SerialzationHelper.BinarySerialize(book); | |
Book book2 = SerialzationHelper.BinaryDeserialize<Book>(data); | |
} |
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
/// <summary> SerialzationHelper Class </summary> | |
public class SerialzationHelper | |
{ | |
/// <summary> Serialize object to binary </summary> | |
/// <param name="obj"> object </param> | |
/// <returns> binary </returns> | |
public static byte[] BinarySerialize(object obj) | |
{ | |
byte[] data; | |
IFormatter formatter = new BinaryFormatter(); | |
using (var stream = new MemoryStream()) | |
{ | |
formatter.Serialize(stream, obj); | |
data = stream.GetBuffer(); | |
} | |
return data; | |
} | |
/// <summary> Deserialize binary to object </summary> | |
/// <typeparam name="T"> object type </typeparam> | |
/// <param name="data"> binary </param> | |
/// <returns> object </returns> | |
public static T BinaryDeserialize<T>(byte[] data) | |
{ | |
T obj; | |
IFormatter formatter = new BinaryFormatter(); | |
using (var stream = new MemoryStream(data)) | |
{ | |
obj = (T)formatter.Deserialize(stream); | |
} | |
return obj; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment