Created
February 14, 2018 15:16
-
-
Save fernandezja/1612068fb0622fd8081ea930d6dee793 to your computer and use it in GitHub Desktop.
Serialize and Deserialize Object To Byte Array (with use Generics) / Serializar y deserializar object to byte array (utilizando Generics)
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.Collections; | |
using System.IO; | |
using System.Runtime.Serialization.Formatters.Binary; | |
namespace SerializeObjectToByteArray | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var hashTable = new Hashtable(); | |
hashTable.Add(1, new Jedi { Id = 11, Name= "Yoda" }); | |
hashTable.Add(2, new Jedi { Id = 22, Name= "Luke Skywalker" }); | |
hashTable.Add(3, new Jedi { Id = 33, Name= "Obi-Wan Kenobi" }); | |
hashTable.Add(4, new Jedi { Id = 44, Name = "Qui-Gon Jinn" }); | |
var dataSerialize = ObjectToByteArray(hashTable); | |
string dataSerializeText = System.Text.Encoding.UTF8.GetString(dataSerialize); | |
Console.WriteLine("Data Serialize Byte Array: "); | |
Console.WriteLine(dataSerializeText); | |
var hashTableUnserialize = ByteArrayToObject<Hashtable>(dataSerialize); | |
foreach (var key in hashTableUnserialize.Keys) | |
{ | |
var jedi = (Jedi)hashTableUnserialize[key]; | |
Console.WriteLine("Jedi {0} > {1}", jedi.Id, jedi.Name); | |
} | |
Console.ReadKey(); | |
} | |
private static byte[] ObjectToByteArray(object obj) | |
{ | |
if (obj == null) | |
return null; | |
BinaryFormatter bf = new BinaryFormatter(); | |
using (MemoryStream ms = new MemoryStream()) | |
{ | |
bf.Serialize(ms, obj); | |
return ms.ToArray(); | |
} | |
} | |
private static T ByteArrayToObject<T>(byte[] data) | |
{ | |
using (MemoryStream ms = new MemoryStream()) | |
{ | |
var binaryFormatter = new BinaryFormatter(); | |
ms.Write(data, 0, data.Length); | |
ms.Seek(0, SeekOrigin.Begin); | |
T obj = (T)binaryFormatter.Deserialize(ms); | |
return obj; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment