Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
Like this article? We recommend

Reading in the Data

The code for reading the data follows the same approach as for saving the data, but the stream goes in reverse:

Private Sub LoadFromFile(ByVal Filename As String)
  Dim formatter As New Runtime.Serialization.Formatters.Binary.BinaryFormatter
  Dim stream As New FileStream(Filename, FileMode.Open, _
    FileAccess.Read, FileShare.Read)
  TextValues = formatter.Deserialize(stream)
  stream.Close()
End Sub

Private Sub OpenToolStripButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles OpenToolStripButton.Click
  If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
    LoadFromFile(OpenFileDialog1.FileName)
  End If
End Sub

Notice that I used a separate subroutine for the code to do the work. As you’ll see later in this article, I’m using that routine elsewhere as well. This code displays an OpenFileDialog window, letting the user choose which file to load. Then, if the user clicks OK, the code in the If block runs, which calls the code to open the file.

This LoadFromFile routine is much like the code described earlier. It creates a BinaryFormatter instance and then a stream, which is readable this time instead of writeable. Then I call the Deserialize method of the BinaryFormatter object. This method takes the stream as a parameter, and returns a new instance of the class that was read in.

If you have Option Strict turned on (which is usually a good idea), the preceding code will fail in the call to Deserialize. In that case, you need to cast your results like so:

TextValues = CType(formatter.Deserialize(stream), TextSettings)

Note also that the Deserialize method creates a new instance; you don’t need to first call New. Thus, TextValues can be declared like this, without a call to New:

Dim TextValues As TextSettings

That’s all there is to reading the data back in.

  • + Share This
  • 🔖 Save To Your Account