I have a byte array, for example:
Dim byteArray(10) as Byte
byteArray(0) = 1
byteArray(1) = 2
byteArray(2) = 3
...
byteArray(9) = 10
and I am trying to convert it into an object but without success. I have read a lot of posts here about on how to do it so I have below function:
Public Shared Function ByteArrayToObject(ByVal arrBytes As Byte()) As Object
Using ms As New MemoryStream()
Dim binForm As New BinaryFormatter()
ms.Write(arrBytes, 0, arrBytes.Length)
ms.Seek(0, SeekOrigin.Begin)
Dim obj As Object = DirectCast(binForm.Deserialize(ms), Object)
Return obj
End Using
End Function
but when performing the DirectCast I am getting an exception saying, more or less (translated from spanish):
"SerializationException was unhandled: End of sequence reached before terminating analysis".
Any idea why is it happening?
You have an array of bytes:
Which is this byte stream:
But you don't have a serialized object. Which is what your code assumes:
That stream can't be de-serialized into an instance of
Objectbecause, well, it isn't a serialized instance ofObject. But this is (or at least is on my machine in my test):Basically, you can't just de-serialize anything into an instance of an object. It has to be an actual serialized version of that object.