Can't Deserialize a Hashtable using a Memory Stream...

G

Guest

The following code explains my problem. It works fine if I use a file
stream, but not if I use a memory stream. What's the problem here? It must
be something simple I am missing...

Dim H As New Hashtable
H.Add(1, "First Item")
H.Add(2, "Second Item")
H.Add(3, "Third Item")

Dim BF As New
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
Dim MS As New IO.MemoryStream
Dim FS As New IO.FileStream("TestFile", IO.FileMode.Create)

BF.Serialize(MS, H)
BF.Serialize(FS, H)
Dim B As Byte() = MS.ToArray

MS.Close()
FS.Close()

'----------------- So Far So Good, now I attempt to De-Serialize

Dim I As New Hashtable
Dim MS2 As New IO.MemoryStream
Dim FS2 As New IO.FileStream("TestFile", IO.FileMode.Open)

I = DirectCast(BF.Deserialize(FS2), Hashtable)
'This works:
MsgBox(I(3))

MS2.Write(B, 0, B.Length)
'This creates the error:
I = DirectCast(BF.Deserialize(MS2), Hashtable)

MsgBox(I(3))

'The Error is: "End of Stream encountered before parsing was
completed."
 
T

Tom Shelton

The following code explains my problem. It works fine if I use a file
stream, but not if I use a memory stream. What's the problem here? It must
be something simple I am missing...

Dim H As New Hashtable
H.Add(1, "First Item")
H.Add(2, "Second Item")
H.Add(3, "Third Item")

Dim BF As New
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
Dim MS As New IO.MemoryStream
Dim FS As New IO.FileStream("TestFile", IO.FileMode.Create)

BF.Serialize(MS, H)
BF.Serialize(FS, H)
Dim B As Byte() = MS.ToArray

MS.Close()
FS.Close()

'----------------- So Far So Good, now I attempt to De-Serialize

Dim I As New Hashtable
Dim MS2 As New IO.MemoryStream
Dim FS2 As New IO.FileStream("TestFile", IO.FileMode.Open)

I = DirectCast(BF.Deserialize(FS2), Hashtable)
'This works:
MsgBox(I(3))
MS2.Write(B, 0, B.Length)
'**************************
' add this line...
MS2.Seek (0, SeekOrigin.Begin)
'******************************
'This creates the error:
I = DirectCast(BF.Deserialize(MS2), Hashtable)

MsgBox(I(3))

'The Error is: "End of Stream encountered before parsing was
completed."

You need to move the position pointer back to the begining of the stream
:)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top