Deserializing from string

  • Thread starter Thread starter Chris
  • Start date Start date
C

Chris

I need to serialise a business object into a session as a string. The reason
for this is that we have to run session state with classic ASP and the code
we use in effect mean ASP.net sessions can only handle strings. My initial
thought is to serialize the object into a string and put it into the session
but I am having problem deserializing it.

Code to serialise
login = New login.clsLogin
Dim objStream As New MemoryStream
Dim objFormatter As New BinaryFormatter

objFormatter.Serialize(objStream, login)
Session("login") = login

Code to deserialise

Dim objFormatter As New BinaryFormatter
Dim enc As New UTF8Encoding
Dim arrBytData() As Byte = enc.GetBytes(Session("login").ToString)
Dim ms As MemoryStream = New MemoryStream()
ms.Write(arrBytData, 0, arrBytData.Length)
ms.Seek(0, 0)
login = objFormatter.Deserialize(ms)

The error I get is:

End of Stream encountered before parsing was completed.

Can anyone point me in the right direction. Regards, Chris.
 
Figured it out

Dim MyFormatter As New BinaryFormatter()
Dim ms As New MemoryStream
MyFormatter.Serialize(ms, login)

Dim bytearray As Byte() = ms.ToArray()
Dim str As String = Convert.ToBase64String(bytearray)
Session("login") = str


Dim objFormatter As New BinaryFormatter
Dim GenericObject As Object
Dim arrBytData() As Byte =
Convert.FromBase64String(Session("login").ToString)
Dim ms As MemoryStream = New MemoryStream(arrBytData)

ms.Write(arrBytData, 0, arrBytData.Length)
ms.Seek(0, SeekOrigin.Begin)
GenericObject = objFormatter.Deserialize(ms)
login = CType(GenericObject, login.clsLogin)
 
Back
Top