18.01.2013 Views

Mastering Visual Basic .NET

Mastering Visual Basic .NET

Mastering Visual Basic .NET

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

526<br />

Chapter 11 STORING DATA IN COLLECTIONS<br />

Dim Shapes As New ArrayList()<br />

Dim R1 As Rectangle<br />

Shapes = CType(BFormatter.Deserialize(readFile), ArrayList)<br />

Dim i As Integer<br />

TextBox1.AppendText(“The ArrayList contains “ & Shapes.Count & _<br />

“ objects” & vbCrLf & vbCrLf)<br />

For i = 0 To Shapes.Count - 1<br />

TextBox1.AppendText(Shapes(i).ToString & vbCrLf)<br />

Next<br />

End Sub<br />

You can find the code presented in this section in the Serialization project on the CD. The<br />

application consists of two buttons; the first persists the collection to disk, and the second reads<br />

the file, re-creates the collection, and displays the objects read from the file.<br />

Persisting a HashTable<br />

We can now return to the WordFrequencies project and examine the code behind the menu of the<br />

project. The Frequency Table menu contains four commands, which save the HashTable to, and<br />

read it from, a text file and a binary file. The four commands of the menu are:<br />

Command Effect<br />

Save Binary Saves the HashTable to a binary file with default extension BIN<br />

Load Binary Loads the HashTable with data from a binary file<br />

Save SOAP Saves the HashTable to a text file with default extension TXT<br />

Load Binary Loads the HashTable with data from a text file<br />

The code behind the Save Binary command is shown in Listing 11.23. The code is actually quite<br />

simple: it creates an instance of the BinaryFormatter class (variable Formatter) and uses its Serialize<br />

method to persists the entire HashTable with a single statement.<br />

Listing 11.23: Persisting the HashTable to a Binary File<br />

Private Sub SaveBin(ByVal sender As System.Object, _<br />

ByVal e As System.EventArgs) Handles SaveBinary.Click<br />

Dim saveFile As FileStream<br />

SaveFileDialog1.DefaultExt = “BIN”<br />

If SaveFileDialog1.ShowDialog = DialogResult.OK Then<br />

saveFile = File.OpenWrite(SaveFileDialog1.FileName)<br />

saveFile.Seek(0, SeekOrigin.End)<br />

Dim Formatter As BinaryFormatter = New BinaryFormatter()<br />

Formatter.Serialize(saveFile, WordFrequencies)<br />

saveFile.Close()<br />

End If<br />

End Sub

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!