Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
(ebook) Visual Studio .NET Mastering Visual Basic.pdf
Скачиваний:
120
Добавлен:
17.08.2013
Размер:
15.38 Mб
Скачать

THE SERIALIZER CLASS 525

not printable. You will still be able to read the names of the properties saved to the file, as shown in Figure 11.6.

Figure 11.6

Viewing a file with objects persisted with the Serializer class

Deserializing Objects

To read a file with the description of an object that has been persisted with the Serialize method, you simply call the Formatter object’s Deserialize method and assign the result to an appropriately declared variable. In the case of the last example, the value returned by the Deserialize method must be assigned to an ArrayList variable. The syntax of the Deserialize method is

object = Bformatter.Deserialize(str)

where str is a Stream object to the file with the data.

Because the Deserialize method returns an Object variable, you must cast it to the ArrayList type with the CType() function. To use the Deserialize method, declare a variable that can hold the value returned by the method. If the data to be deserialized is a Rectangle, declare a Rectangle variable. If it’s a collection, declare a variable of the same collection type. Then call the Deserialize method and cast the value returned to the appropriate type. The following statements outline the process:

Dim object As <type>

{ code to set up a Stream variable (str) and BinaryFormatter } object = CType(Bformatter.Serialize(str), <type>)

Listing 11.22 is the code that retrieves the items from the ShapesColors.bin file and stores them into an ArrayList. I’ve added a few statements to print all the items of the ArrayList.

Listing 11.22: De-serializing a Collection

Private Sub Button1_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles Button1.Click Dim readFile As FileStream

readFile = File.OpenRead(“C:\ShapesColors.bin”) Dim BFormatter As BinaryFormatter

BFormatter = New BinaryFormatter()

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

526 Chapter 11 STORING DATA IN COLLECTIONS

Dim Shapes As New ArrayList() Dim R1 As Rectangle

Shapes = CType(BFormatter.Deserialize(readFile), ArrayList) Dim i As Integer

TextBox1.AppendText(“The ArrayList contains “ & Shapes.Count & _ “ objects” & vbCrLf & vbCrLf)

For i = 0 To Shapes.Count - 1 TextBox1.AppendText(Shapes(i).ToString & vbCrLf)

Next End Sub

You can find the code presented in this section in the Serialization project on the CD. The application consists of two buttons; the first persists the collection to disk, and the second reads the file, re-creates the collection, and displays the objects read from the file.

Persisting a HashTable

We can now return to the WordFrequencies project and examine the code behind the menu of the project. The Frequency Table menu contains four commands, which save the HashTable to, and read it from, a text file and a binary file. The four commands of the menu are:

Command

Effect

Save Binary

Saves the HashTable to a binary file with default extension BIN

Load Binary

Loads the HashTable with data from a binary file

Save SOAP

Saves the HashTable to a text file with default extension TXT

Load Binary

Loads the HashTable with data from a text file

The code behind the Save Binary command is shown in Listing 11.23. The code is actually quite simple: it creates an instance of the BinaryFormatter class (variable Formatter) and uses its Serialize method to persists the entire HashTable with a single statement.

Listing 11.23: Persisting the HashTable to a Binary File

Private Sub SaveBin(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles SaveBinary.Click Dim saveFile As FileStream

SaveFileDialog1.DefaultExt = “BIN”

If SaveFileDialog1.ShowDialog = DialogResult.OK Then saveFile = File.OpenWrite(SaveFileDialog1.FileName) saveFile.Seek(0, SeekOrigin.End)

Dim Formatter As BinaryFormatter = New BinaryFormatter() Formatter.Serialize(saveFile, WordFrequencies) saveFile.Close()

End If End Sub

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

THE SERIALIZER CLASS 527

The equivalent Load Binary command is just as simple. It sets up a BinaryFormatter object and calls its Deserialize method to read the data.

The code of the Save SOAP command (Listing 11.24) sets up a SoapFormatter object and uses its Serialize method to persist the HashTable. The code that reads the data from the file and populates the HashTable is equally simple, and it’s shown in Listing 11.25.

Listing 11.24: Persisting the HashTable to a Text File

Private Sub SaveText(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles SaveText.Click Dim saveFile As FileStream

SaveFileDialog1.DefaultExt = “XML”

If SaveFileDialog1.ShowDialog = DialogResult.OK Then saveFile = File.OpenWrite(SaveFileDialog1.FileName) saveFile.Seek(0, SeekOrigin.End)

Dim Formatter As Soap.SoapFormatter = New Soap.SoapFormatter() Formatter.Serialize(saveFile, WordFrequencies) saveFile.Close()

End If End Sub

Listing 11.25: Loading a HashTable from a Text File

Private Sub LoadText(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles LoadText.Click Dim readFile As FileStream

OpenFileDialog1.DefaultExt = “XML”

If OpenFileDialog1.ShowDialog = DialogResult.OK Then readFile = File.OpenRead(OpenFileDialog1.FileName) Dim Formatter As Soap.SoapFormatter

Formatter = New Soap.SoapFormatter()

WordFrequencies = CType(Formatter.Deserialize(readFile), SortedList) End If

End Sub

As you can see, the code is identical whether you use the BinaryFormatter or a SoapFormatter class. The code is quite simple, and the Serialize/Deserialize methods do all the work automagically. You can open the binary file with a text editor, and you will see the words but not the numeric values. If you open the text file, you will see a structured XML file with the words and their counts. The words are in the first half of the file, and their counts in the second half. Here are the first few

lines of this file (I’ve omitted the headers):

<item id=”ref-5” xsi:type=”SOAP-ENC:string”>A</item>

<item id=”ref-6” xsi:type=”SOAP-ENC:string”>ABADDIRS</item>

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com