Serialization problem

N

Norman Chong

Hiddeldi ho,

I want to save an object so that I can use its content after I restart
my program. I tried to solve this with serialization because someone
told me that this is the correct way for this.
So I wrote the following code to serialize\deserialize the object, but
now I have the problem that the object has a generic list and when I'm
trying to deserialize it, I get an error.

<System.Serializable()> Public Class TestClass
Implements Runtime.Serialization.ISerializable
Private lstContent As List(Of Object)

Public Sub New(ByVal info As Serialization.SerializationInfo, ByVal
context As Serialization.StreamingContext) Implements
Serialization.ISerializable.GetObjectData
lstContent = CType(info.GetValue("MyList", lstContent.GetType),
List(Of Object))
End Sub

Public Sub GetObjectData(ByVal info As
Serialization.SerializationInfo, ByVal context As
Serialization.StreamingContext) Implements
Serialization.ISerializable.GetObjectData
info.addValue("MyList",lstContent)
End Sub

Public Sub Serialize()
Dim fs As New IO.FileStream("DataFile.dat", IO.FileMode.Create)
' Construct a BinaryFormatter and use it to serialize the data
to the stream.
Dim formatter As New
Runtime.Serialization.Formatters.Binary.BinaryFormatter
Try
formatter.Serialize(fs, Me)
Catch e As Runtime.Serialization.SerializationException
MessageBox.Show("Failed to serialize. Reason: " &
e.Message)
Throw
Finally
fs.Close()
End Try
End Sub

Public Shared Function Deserialize() As TestClass
Dim fs As New IO.FileStream("DataFile.dat", IO.FileMode.Open)
Try
Dim formatter As New
Runtime.Serialization.Formatters.Binary.BinaryFormatter

Return DirectCast(formatter.Deserialize(fs), TestClass)
Catch e As Runtime.Serialization.SerializationException
MessageBox.Show("Failed to deserialize. Reason: " &
e.Message)
Throw
Finally
fs.Close()
End Try
End Function

Can anybody give me an advice to solve my problem please?
Or does anybody know a simpler\better way to save an object?

Thanks,
Norman
 
N

Norman Chong

Steve said:
It might be helpful to know what the error is that you're getting.

Hi Steve
My deserialized object always had the value 'nothing'. But I already
solved the problem (I just forgot to post that - Sorry!)

Thanks,
Norman
 

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