title: Converting byte[] to object in vb.net
body: <p>I have a byte array, for example:</p>
  
  <pre><code>Dim byteArray(10) as Byte
  
  byteArray(0) = 1
  byteArray(1) = 2
  byteArray(2) = 3
  ...
  byteArray(9) = 10
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>but when performing the DirectCast I am getting an exception saying, more or less (translated from spanish):</p>
  
  <pre><code>"SerializationException was unhandled: End of sequence reached before terminating analysis".
  </code></pre>
  
  <p>Any idea why is it happening?</p>