Skip to content

Instantly share code, notes, and snippets.

@allyusd
Last active October 1, 2015 06:24
Show Gist options
  • Save allyusd/fc9850ebd3f1219e6df1 to your computer and use it in GitHub Desktop.
Save allyusd/fc9850ebd3f1219e6df1 to your computer and use it in GitHub Desktop.
C# Serialization
[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; }
}
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);
}
/// <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