|
|
Binary Serialization - Quick and Easy | | For many programmers, serialization is a topic that brings fear. Put those fears to rest in .NET. Serializaing objects is really quite simple. Lets jump right in and try to serialize this simple class:
Public Class Article
Public sTitle As String = String.Empty
Public sAuthor As String = String.Empty
Public sText As String = String.Empty
End Class
|
Not much to this class, just a few string variables. Lets suppose that we need to write an instance of this class out to disk. We may want to use the application to create an article then send it to someone else who has an Article Reader that can read our proprietary article format. To do this, we can use binary serialization. This will create a binary file that can be read back in as an instance of Article. To do this, we will need to implement 2 methods - GetObjectData and an overloaded constructor. First, we need to import some namespaces that we will need:
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
...
|
Now, we will mark the class with the Serializable attribute and implement the ISerializable interface:
<Serializable()> _
Public Class Article
Implements ISerializable
...
|
To implement the interface, we will add the methods metioned earlier. Here is the first:
Public Sub GetObjectData(ByVal info As SerializationInfo, _
ByVal context As StreamingContext) _
Implements ISerializable.GetObjectData
info.AddValue("Title", Title)
info.AddValue("Author", Author)
info.AddValue("Text", Text)
End Sub
|
This method will allow us to serialize the object to disk. We could add any code in here that we wanted to customize the way the data is serialized. For instance, we could serialize additional things that are not even part of the Article class, like a timestamp of when it was serialized, or an id of the user who serialized it.
Now we need a method to retrieve the data from a serialized object. We will use a constructor for this:
Public Sub New(ByVal info As SerializationInfo, _
ByVal context As StreamingContext)
Title = CStr(info.GetValue("Title", GetType(String)))
Author = CStr(info.GetValue("Author", GetType(String)))
Text = CStr(info.GetValue("Text", GetType(String)))
End Sub
Public Sub New()
'Empty Constructor
End Sub
|
Again, we could customize this method as well if we created additional fields in the GetObjectData method. The empty construcor is added here so that you can create a new Article object without deserializing one(which is pretty important since without it you could never create an Article object to serialize).
Now we have a class that can be serialized and deserialized, but how do we actually do it? Let's put that code in the class as well. For serializing, we will just create a method called Serialize (Note that the code could be in another class - it does not have to be in a method called Serialize):
Public Sub Serialize(ByVal Filename As String)
Dim s As Stream
Try
s = File.Open(Filename, FileMode.Create, FileAccess.ReadWrite)
Dim b As New BinaryFormatter
b.Serialize(s, Me)
Finally
s.Close()
End Try
End Sub
|
The code for deserializing is just as easy. We will make this a shared function that returns an instance of the Article class so that the caller can just pass in the filename and get back the object:
Public Shared Function Deserialize(ByVal Filename As String) As Article
Dim s As Stream
Try
s = File.Open(Filename, FileMode.Open, FileAccess.Read)
Dim b As New BinaryFormatter
Return CType(b.Deserialize(s), Article)
Finally
s.Close()
End Try
End Function
|
Our Article class is complete. If we want to open or save an Article object from a form that has Open and Save File Dialogs, we can make some simple method calls:
Private CurrentArticle As Article
...
If Me.OpenFileDialog1.ShowDialog = DialogResult.OK Then
CurrentArticle = Article.Deserialize(Me.OpenFileDialog1.FileName)
End If
...
If Me.SaveFileDialog1.ShowDialog = DialogResult.OK Then
CurrentArticle.Serialize(Me.SaveFileDialog1.FileName)
End If
|
There you have it - binary object serialization. It doesn't require much code, and it will persist your .NET objects as files.
You can download a sample project with all the source code for this article here. |
|