Немного подправленные исходники от
Виталий Пухов:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace Serialization
{
[Serializable]
class MSG
{
public int type;
public string message;
public MSG(int i, string s)
{
type = i;
message = s;
}
}
class Program
{
public static byte[] Serialization(MSG obj)
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, obj);
byte[] msg = stream.ToArray();
return msg;
}
public static MSG DeSerialization(byte[] serializedAsBytes)
{
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
stream.Write(serializedAsBytes, 0, serializedAsBytes.Length);
stream.Seek(0, SeekOrigin.Begin);
return (MSG)formatter.Deserialize(stream);
}
public static void Main(string[] args)
{
MSG msg = new MSG(65456541, "Я нasdsadsadsdafvdsafvbе сериализован");
MSG msg1;
byte[] buf = new byte[1024];
buf = Serialization(msg);
Console.WriteLine("До сериализации " + msg.type + "|" + msg.message);
msg1 = DeSerialization(buf);
Console.WriteLine("После сериализации " + msg1.type + "|" + msg1.message);
Console.ReadKey(true);
}
}
}