Code Repo    |     RSS
MD's Technical Sharing



Wednesday, October 8, 2008

Serializing/De-serializing an ArrayList

Declarations:


'Type of each element in the ArrayList
Public Structure ArrayListEntry

End Structure

'ArrayList containing elements of above type
Public myArrayList As New ArrayList


Declare a custom serializer:


Dim customSerializer As New XmlSerializer(GetType(Object()), New System.Type() {GetType(ArrayListEntry)})


Methods to serialize data into XML:


A custom serializer must be used.


Public Sub saveSerializedData(ByVal datafile As String, ByVal ConfigObj As Object, ByVal serializer as XmlSerializer) As Boolean
Dim writer As New StreamWriter(datafile)
serializer.Serialize(writer, ConfigObj)
writer.Close()
End Sub


To use the method:


saveSerializedData("out.xml", myArrayList.ToArray, customSerializer)


Method to de-serialize data back to Object:


Public Function readSerializedData(ByVal datafile As String, ByRef ConfigType As Type) As Object
Dim retConf As Object = Nothing
Dim serializer As XmlSerializer = New XmlSerializer(ConfigType)
Dim fs As New FileStream(datafile, FileMode.Open)
retConf = serializer.Deserialize(fs)
fs.Close()
Return retConf
End Function


To use the method:


myArrayList.AddRange(CType(readSerializedData("out.xml", myArrayList.GetType, isok, customSerializer), Collections.ICollection))

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.