Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Imports System.IO
- Imports System.Collections
- Imports System.Runtime.Serialization.Formatters.Binary
- Imports System.Runtime.Serialization
- Imports System.Xml.Serialization
- Module Module1
- Sub Main()
- ' Create a List of values that will eventually be serialized.
- Dim EmployeeList1 As New List(Of Employee)()
- EmployeeList1.Add(New Employee(1, "Elenor", "Scheller"))
- EmployeeList1.Add(New Employee(2, "Kaila", "Wilburn"))
- EmployeeList1.Add(New Employee(3, "Shea", "Wallen"))
- EmployeeList1.Add(New Employee(4, "Elliot", "Shaffer"))
- EmployeeList1.Add(New Employee(5, "Dominica", "Charney"))
- Serialize(EmployeeList1)
- Dim EmployeeList2 As New List(Of Employee)(Deserialize())
- ' display the results
- For Each Employee In EmployeeList2
- Console.WriteLine("{0}, {1}, {2}",
- Employee.id,
- Employee.fName,
- Employee.sName)
- Next
- Console.ReadLine()
- End Sub
- Private Sub Serialize(EmployeeList As List(Of Employee))
- ' Use a file stream here.
- Using WriteFileStream As New StreamWriter("test.xml")
- ' Construct a SoapFormatter and use it
- ' to serialize the data to the stream.
- Dim SerializerObj As New XmlSerializer(GetType(List(Of Employee)))
- Try
- ' Serialize EmployeeList to the file stream
- SerializerObj.Serialize(WriteFileStream, EmployeeList)
- Catch ex As Exception
- Console.WriteLine(String.Format("Failed to serialize. Reason: {0}", ex.Message))
- End Try
- End Using
- End Sub
- Private Function Deserialize() As List(Of Employee)
- Dim EmployeeList2 = New List(Of Employee)()
- ' Create a new file stream for reading the XML file
- Using ReadFileStream = New FileStream("test.xml", FileMode.Open, FileAccess.Read, FileShare.Read)
- ' Construct a XmlSerializer and use it
- ' to serialize the data from the stream.
- Dim SerializerObj = New XmlSerializer(GetType(List(Of Employee)))
- Try
- ' Deserialize the hashtable from the file
- EmployeeList2 = DirectCast(SerializerObj.Deserialize(ReadFileStream), List(Of Employee))
- Catch ex As Exception
- Console.WriteLine(String.Format("Failed to serialize. Reason: {0}", ex.Message))
- End Try
- End Using
- ' return the Deserialized data.
- Return EmployeeList2
- End Function
- End Module
- ' The object we are going to Serializing/De-serializing
- <Serializable()>
- Public Class Employee
- Property id As Integer
- Property fName As String
- Property sName As String
- Public Sub New()
- End Sub
- Public Sub New(i As Integer, f As String, s As String)
- id = i
- fName = f
- sName = s
- End Sub
- End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement