Serialization and deserialization of object
Public Function add() As TestClass
Dim obj As TestClass
obj = New TestClass
//Test is a propert of class TestClass
//Populate the object
obj.Test = "Hello"
Dim serializer As New XmlSerializer(GetType(TestClass))
Dim st As String = TestClassXml(obj)
Dim fileExists As Boolean
fileExists = My.Computer.FileSystem.FileExists("C:\Test.xml")
If fileExists Then
My.Computer.FileSystem.DeleteFile("C:\Test.xml", FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.DeletePermanently)
End If
My.Computer.FileSystem.WriteAllText("C:\Test.xml", st, True)
Dim fileContents As String
fileContents = My.Computer.FileSystem.ReadAllText("C:\Test.xml")
stream = New IO.StringReader(fileContents)
' read xml data
reader = New XmlTextReader(stream)
' create reader
Return DirectCast(serializer.Deserialize(reader), TestClass)
End Function
------------------------------------
Function to convert object to xml
-------------------------------------
Public Function TestClassXml(ByVal obj As TestClass) As String
Dim stream As IO.MemoryStream = Nothing
Dim writer As IO.TextWriter = Nothing
stream = New IO.MemoryStream()
' read xml in memory
writer = New IO.StreamWriter(stream, Encoding.UTF8)
' get serialise object
Dim serializer As New XmlSerializer(GetType(TestClass))
serializer.Serialize(writer, obj)
' read object
Dim count As Integer = CInt(stream.Length)
' saves object in memory stream
Dim arr As Byte() = New Byte(count - 1) {}
stream.Seek(0, IO.SeekOrigin.Begin)
' copy stream contents in byte array
stream.Read(arr, 0, count)
Dim utf As New UTF8Encoding
' convert byte array to string
Return utf.GetString(arr).Trim()
End Function