Visual Basic 2010 : Objects Serialization (part 1) - Binary Serialization
Binary Serialization
The following example shows how you can serialize a typed collection of strings into a file on disk using the BinaryFormatter class:
Dim stringSeries As New List(Of String) From
{"Serialization", "demo",
"with VB"}
Dim targetFile As New _
FileStream("C:\temp\SerializedData.dat",
FileMode.Create)
Dim formatter As New BinaryFormatter
formatter.Serialize(targetFile, stringSeries)
targetFile.Close()
formatter = Nothing
Note
The above code example requires Imports System.IO and Imports System.Runtime.Serialization.Formatters.Binary directives.
The code simply creates a new file named SerializedData.Dat and puts the result of the binary serialization in the file. If you examine the content of the file with the Windows Notepad, you can obtain a result similar to what is shown in Figure 1.
Figure 1. Examining the result of the serialization process.
You don’t effectively need to know how your objects are serialized, but it is interesting to understand what kind of information is placed into the target file, such as the serialized type, assembly information, and the actual data. To deserialize a binary file you simply invoke the BinaryFormatter.Deserialize method, as shown in the following code which you write right after the preceding example:
Dim sourceFile As New FileStream("C:\temp\SerializedData.dat",
FileMode.Open)
formatter = New BinaryFormatter
Dim data = CType(formatter.Deserialize(sourceFile),
List(Of String))
sourceFile.Close()
formatter = Nothing
'Iterates the result
For Each item In data
Console.WriteLine(item)
NextNotice that Deserialize returns Object; therefore, the result needs to be converted into the appropriate type that you expect. If you run the preceding code you see on your screen how the strings from the collection are correctly listed. This kind of serialization is also straightforward because it enables serializing entire object graphs. Moreover, you can use this technique against user interface controls in Windows Forms and WPF applications to persist the state of your interface objects that can be later re-created.
Creating Objects Deep Copies with Serialization
The code in Listing 1 shows how to accomplish this by implementing a generic method.
Listing 1. Implementing Deep Copy with Serialization
Because you are not limited to file streams, taking advantage of a memory stream is good in such a scenario. You invoke the preceding method as follows:
Dim result As Object = CreateDeepCopy.Clone(objectToClone)
You could also implement extension methods for providing deep copy to all types.