Serializing a Structure

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Does anyone know why this code gives an error:

<serializeable> public structure TestSerialize
anumber as integer
astring as string
end strucuture

Dim t As TestSerialize
Dim formatter As New BinaryFormatter
Dim s As New MemoryStream
t.anumber = 125
t.astring = "This is a test of Serialilzing a structure"
formatter.Serialize(s, t)
t = DirectCast(formatter.Deserialize(s), TestSerialize) ' This lines give
an error
saying that end of memory stream found before parsing was completed.
 
Why do you want to serialize to a memorystream and not a filestream? Here
are some example of each:

<Serializable()> Public Structure TestSerialize
Dim anumber As Integer
Dim astring As String
End Structure


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
' serialzie to memorystream
Dim t1 As TestSerialize
t1.anumber = 125
t1.astring = "This is a test of Serialilzing a structure"

Dim formatter As New BinaryFormatter

Dim ms As New MemoryStream
formatter.Serialize(ms, t1)

Dim t2 As TestSerialize
ms.Seek(0, SeekOrigin.Begin) ' think this was what you were missing

t2 = DirectCast(formatter.Deserialize(ms), TestSerialize)
ms.Close()

Debug.WriteLine(t2.anumber)
Debug.WriteLine(t2.astring)

End Sub


Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
' serialzie to filestream
Dim t1 As TestSerialize
t1.anumber = 125
t1.astring = "This is a test of Serialilzing a structure"

Dim formatter As New BinaryFormatter
Dim fs As New FileStream("c:\test.bin", FileMode.Create,
FileAccess.Write)

formatter.Serialize(fs, t1)
fs.Close()

Dim t2 As TestSerialize

fs = New FileStream("c:\test.bin", FileMode.Open, FileAccess.Read)
t2 = DirectCast(formatter.Deserialize(fs), TestSerialize)
fs.Close()

Debug.WriteLine(t2.anumber)
Debug.WriteLine(t2.astring)
End Sub

HTH,
Greg
 
Thanks a lot...that works.

Just to answer your question about serializing to memory instead of file:

I have a very complex structure containing reference objects that I want to
make a deep copy of from one variable to another. I currently have a
separate copy routine that does it but I was just looking for a simpler way
and thought that maybe I could serialize one variable to memor then
deserialize it to another thus making a keep copy of my original variable.

Thanks again for you help.
 

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

Back
Top