简体   繁体   中英

Converting byte[] to object in vb.net

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:

Dim byteArray(10) as Byte

byteArray(0) = 1
byteArray(1) = 2
byteArray(2) = 3
...
byteArray(9) = 10

Which is this byte stream:

1 2 3 4 5 6 7 8 9 10

But you don't have a serialized object . Which is what your code assumes:

Dim obj As Object = DirectCast(binForm.Deserialize(ms), Object)

That stream can't be de-serialized into an instance of Object because, well, it isn't a serialized instance of Object . But this is (or at least is on my machine in my test):

0 1 0 0 0 255 255 255 255 1 0 0 0 0 0 0 0 4 1 0 0 0 13 83 121 115 116 101 109 46 79 98 106 101 99 116 0 0 0 0 11

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM