Avoid Using Dynamic SQL StatementsBeware of the Byte Order Mark

Using Binary Serialization

May 25th, 2007

Scotty, beam up my objects.Binary Serialization is the process of storing the state of an object in a binary stream. The public and private members of the object as well as the name of the class are converted to a stream of bytes. This data can be written to disk, transmitted, or other managed in other ways that are applicable to data streams. When the object is deserialized, an exact clone of the original object is created. Think of it as a Star Trek style transporter for your objects.

This simple example shows how to save and restore the contents of a listbox using Binary Serialization. In the application, the program reads the listbox data from disk, if it exists, then the user enters new items into the listbox. They may also clear one, many, or all of the items from the list and save the data if they wish. Finally, when the program is closed the user has the option to save the data to disk again. Let’s look at some of the details.

First, we have to setup our references right to use Binary Serialization. We will need use the following:

Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary

They should be loaded as the default references but you will need to import them or type quite a long line of code to reference them.

Next, in the Form’s load routine we see how to use the BinaryFormatter:

Using fs As New IO.FileStream(_dataFile, IO.FileMode.Open, IO.FileAccess.Read)
    lstItems.Items.AddRange(DirectCast(New BinaryFormatter().Deserialize(fs), Object()))
End Using

Note that we put the FileStream in a Using block to insure that it releases the file after it reads in the data. See my article on Using for more details on this. In the block we use the AddRange method of the Listbox’s Items collection to load the deserialized Object array contents into the listbox.

Why did we need to use an Object array rather than the Listbox’s built-in ObjectCollection? The reason for this is that the ObjectCollection is not serializable. In order for an object to be serialized it needs to be built that way and the ObjectCollection nor the Listbox itself are serializable. So, we will need to convert the items to and from Object arrays in this case. In your own classes you want to serialize, use the Serializable attribute to mark it this way, as in this example:

<Serializable()> _
Public Class MyClass

Also, we use DirectCast insure that .NET knows exactly what kind of object we’re expecting to be loaded.

Now, when we’re prepared to save the listbox data, we reverse the process. Once again we use the Using block for FileStream operations.

Using fs As New FileStream(_dataFile, IO.FileMode.Create)
     Dim items(lstItems.Items.Count - 1) As Object
     lstItems.Items.CopyTo(items, 0)
     Dim bf As New BinaryFormatter
     bf.Serialize(fs, items)
     fs.Close()
End Using

Next, we will need to copy the ListBox’s items from its ObjectCollection to an object array in order to serialize it. We do this by using the CopyTo method. Next the array is serialized to the FileStream and we’re done.

Binary serialization is a effective tool to use when you need to persist data without a using a database or when you want to transfer data from one location to another. Web Services often use it or its cousins XML and SOAP serialization to transfer data. It’s a great tool to add to your VB.NET bag of tricks.


ยป Click here to download VB.NET source code for this article.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

Entry Filed under: Code Examples


Rate This Article:

Not That GoodCould Be BetterOKGoodGreat (3 votes, average: 5 out of 5)
Loading ... Loading ...

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Visit Me At My New Site, Programming In C#

Most Popular Articles

Highest Rated Articles

Categories

Most Recent Articles

Feeds

 Subscribe in a reader

To subscribe by e-mail
Enter your address here

Delivered by FeedBurner

VB Opportunities

Archives