Serialization

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

Guest

Hell
I would like to use a seriazation to save one object at the moment and then another one... and antother one... And if I need read them all back. Is there a nice way to do it ? Beacause in all tutorials there are example how to save one object or arraylist of objects... But let's say this array has a 100000 of objects is it good idea to save a whole array after I add one object ? Won't it be a little slow ?
Jarod
 
Hi,

I converted the code in the 101 vb.net samples How-To Serializing
Objects to work with an array. Here are the changes to the binary
serialization. Hope this helps.

Private Sub cmdStandardSerializationBinary_Click(ByVal sender As
System.Object, _
ByVal e As System.EventArgs) _
Handles cmdStandardSerializationBinary.Click
'This routine creates a new instance of Class1, then serializes it to
'the file Class1File.dat using the Binary formatter.

'Create the object to be serialized
Dim c(500) As Class1

For x As Integer = 0 To 500
c(x) = New Class1(CInt(Rnd() * 200), CInt(Rnd() * 100),
CInt(Rnd() * 200))
Next

'Get a filestream that writes to strFilename2
Dim fs As New FileStream(strFileName2, FileMode.OpenOrCreate)

'Get a Binary Formatter instance
Dim bf As New BinaryFormatter

'Serialize c to strFileName2
bf.Serialize(fs, c)

'Close the file and release resources (avoids GC delays)
fs.Close()

'Deserialization is now available
cmdStandardDeserializationBinary.Enabled = True

End Sub

Private Sub cmdStandardDeserializationBinary_Click(ByVal sender As
System.Object, _
ByVal e As System.EventArgs) _
Handles cmdStandardDeserializationBinary.Click
'This routine deserializes an object from the file Class1File.dat
'and assigns it to a Class1 reference.

'Declare the reference that will point to the object to be deserialized
Dim c() As Class1

'Get a filestream that reads from strFilename2
Dim fs As New FileStream(strFileName2, FileMode.Open)

'Get a Binary Formatter instance
Dim bf As New BinaryFormatter()

'Deserialize c from strFilename2
'Note that the deserialized object must be cast to the proper type.
c = CType(bf.Deserialize(fs), Class1())

'Close the file and release resources (avoids GC delays)
fs.Close()

'Put the deserialized values for the fields into the textboxes
txtXAfter.Text = CStr(c(0).x)
txtYAfter.Text = CStr(c(0).GetY)
txtZAfter.Text = CStr(c(0).z)

For x As Integer = 0 To c.GetUpperBound(0)
Trace.WriteLine(String.Format("{0} = {1}, {2}, {3}", x, c(x).x,
c(x).GetY, c(x).z))
Next
'Reset button after deserializing
cmdStandardDeserializationBinary.Enabled = False

End Sub

Ken
 
Back
Top