There is the following class:
[Serializable] public class Packet : ISerializable { private byte[] _userId; private byte[] _userMessage; public Packet() { } public Packet(byte[] userId, byte[] userMessage) { UserMessage.CopyFrom(ref _userMessage, userMessage); UserId.CopyFrom(ref _userId, userId); } protected Packet(SerializationInfo info, StreamingContext context) { UserId = info.GetValue(nameof(_userId), typeof(byte[])).To<byte[]>(); UserMessage = info.GetValue(nameof(_userMessage), typeof(byte[])).To<byte[]>(); } public byte[] UserId { get => _userId; set => _userId = value; } public byte[] UserMessage { get => _userMessage; set => _userMessage = value; } public byte[] ByteData { get { byte[] dataBytes; using (MemoryStream stream = new MemoryStream()) { BinaryFormatter fmt = new BinaryFormatter(); fmt.Serialize(stream, this); dataBytes = new byte[stream.GetBuffer().Length]; dataBytes.CopyFrom(stream.GetBuffer()); } return dataBytes; } } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue(nameof(_userId), _userId, typeof(byte[])); info.AddValue(nameof(_userMessage), _userMessage, typeof(byte[])); } } And a small test to check the class:
byte[] userId = new byte[256]; for (int i = 0; i < 256; i++) { userId[i] = (byte)i; } Packet packet = new Packet(userId, userId); byte[] data = packet.ByteData; Packet endDataPacket = new Packet(); using (MemoryStream stream = new MemoryStream()) { BinaryFormatter fmt = new BinaryFormatter(); stream.Write(data, 0, data.Length); endDataPacket = fmt.Deserialize(stream).To<Packet>(); } And a small class of extensions:
public static class Extensions { public static T To<T>(this object self) { return (T) self; } public static void CopyFrom(this byte[] source, byte[] from) { Array.Copy(from, source, from.Length); } public static void CopyFrom(this byte[] self, ref byte[] source, byte[] from) { if (source == null) source = new byte[from.Length]; source.CopyFrom(from); } //public static T2 ArrayRemap<T, T2>(this T self, T2 destType) where T2 : IEnumerable<T2> where T : IEnumerable<T> //{ // T2[] tmpData = new T2[self.To<IEnumerable<T>>().Count()]; //} } Next, when I serialize an object, everything is fine, but when I try to deserialize it, I get the following:
An exception was thrown: "System.Runtime.Serialization.SerializationException" in mscorlib.dll An exception like "System.Runtime.Serialization.SerializationException" occurred in mscorlib.dll, but was not processed in the user code. The end of the stream was detected before the parsing was completed.
What could be the reason for this behavior?