Home

File Processing: Reading From a Stream

   

Binary ReadingĀ 

As opposed to writing to a stream, you may want to read existing data from it. Before doing this, you can first specify your intent to the streaming class using the FileMode enumerator. This can be done using the FileStream class as follows:

Private Sub btnOpen_Click(ByVal sender As Object, _
                              ByVal e As System.EventArgs) _
                              Handles btnOpen.Click

        Dim Filename As String = "Persons.prs"

        Dim PersonsStreamer As FileStream = _
            New FileStream(Filename, FileMode.Create)
End Sub
 

Once the stream is ready, you can get prepared to read data from it. To support this, you can use the BinaryReader class. This class provides two constructors. One of the constructors (the first) has the following syntax:

Public Sub New(input As Stream)

This constructor takes as argument a Stream value, which could be a FileStream object. After declaring a FileStream variable using this constructor, you can read data from it. To support this, the class provides an appropriate method for each primitive data type.

After using the stream, you should close it to reclaim the resources it was using. This is done by calling the Close() method.

Here is an example of using the mentioned methods:

Private Sub btnOpen_Click(ByVal sender As Object, _
                              ByVal e As System.EventArgs) _
                              Handles btnOpen.Click

        Dim Filename As String = "Persons.prs"
        Dim PersonsStreamer As FileStream
        Dim PersonsReader As BinaryReader

        PersonsStreamer = New FileStream(Filename, FileMode.Open)
        PersonsReader = New BinaryReader(PersonsStreamer)

        txtPerson1.Text = PersonsReader.ReadString()
        txtPerson2.Text = PersonsReader.ReadString()
        txtPerson3.Text = PersonsReader.ReadString()
        txtPerson4.Text = PersonsReader.ReadString()

        PersonsReader.Close()
        PersonsStreamer.Close()
End Sub

Stream Reading

Besides the BinaryReader class that reads its values in binary format, the .NET Framework supports character reading through a class called StreamReader. The StreamReader class is based on the TextReader class. Like its counterpart the StramWriter class, StreamReader is equipped with various constructors. If you want to read values from a file, you can pass its name or path to the following constructor:

Public Sub New(path As String)

Alternatively, to a FileStream object, you can pass it to the following constructor of the StreamReader class to create a stream:

Public Sub New (stream As Stream)

This method takes as argument a Stream-based variable, which could be a FileStream value. If/since you are planning to read from a stream, configure your file mode status appropriately. Here is an example:

Private Sub btnOpen_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles btnOpen.Click
        Dim Filename As String = "Student.std"

        Dim StudentsStreamer As FileStream
        Dim StudentsReader As StreamReader

        StudentsStreamer = New FileStream(Filename, FileMode.Open)
        StudentsReader = New StreamReader(StudentsStreamer)
End Sub

After creating a StreamReader object, you can read data from the file. To support this, the TextReader class is equipped with the Write() method that the StreamReader class inherits. The StreamReader class itself is equipped with the ReadLine() method. Here is an example of calling it:

Private Sub btnOpen_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles btnOpen.Click
        Dim Filename As String = "Student.std"

        Dim StudentsStreamer As FileStream
        Dim StudentsReader As StreamReader

        StudentsStreamer = New FileStream(Filename, FileMode.Open)
        StudentsReader = New StreamReader(StudentsStreamer)

        txtFirstName.Text = StudentsReader.ReadLine()
        txtLastName.Text = StudentsReader.ReadLine()
        cbxGenders.SelectedIndex = CInt(StudentsReader.ReadLine())

        StudentsReader.Close()
        StudentsStreamer.Close()
End Sub

Using My File System

To read text from a file using the FileSystem class from My object, you can call the OpenTextFileReader() method. It comes in two versions whose syntaxes are:

Public Shared Function OpenTextFileReader( _
   ByVal file As String, 
) As System.IO.StreamReader

Public Shared Function OpenTextFileReader( _
   ByVal file As String, _
   ByVal encoding As System.Text.Encoding _
) As System.IO.StreamReader

The first argument is the name of, or the path to, the file that will receive the new values. The encoding argument allows you to specify the type of text that you want to use.

This method returns a StreamReader value. After creating the stream reader, you can then read values from it. To do this, you can call the ReadLine() method of the StreamReader class. Once again, after using the stream reader, remember to close it. Here are examples:

Private Sub Button2_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles Button2.Click
        Dim fstPeople As StreamReader

        fstPeople = My.Computer.FileSystem.OpenTextFileReader("People1.ppl")

        txtPerson1.Text = fstPeople.ReadLine
        txtPerson2.Text = fstPeople.ReadLine
        txtPerson3.Text = fstPeople.ReadLine
        txtPerson4.Text = fstPeople.ReadLine

        fstPeople.Close()
End Sub

Practical LearningPractical Learning: Reading From a Stream

  1. Access the Code and, in the Class Name combo box, select (Exercise Events)
  2. In the Method Name combo box, select Load and implement the event as follows:
    Private Sub Exercise_Load(ByVal sender As Object, _
                                  ByVal e As System.EventArgs) _
                                  Handles Me.Load
            Dim OrderDate As String, OrderTime As String
            Dim SelectedFlavor As String
            Dim SelectedContainer As String
            Dim SelectedIngredient As String
            Dim Scoops As String, OrderTotal As String
            Dim Filename As String
            Dim IceCreamReader As StreamReader
    
            Filename = InputBox( _
                   "If you had previously ordered an ice cream here " & _
                   "and you want to order the same, please type your " & _
                   "initials and press Enter (otherwise, press Esc)", _
                   "Ice Cream Vending Machine", "", 100, 100)
            If Filename <> "" Then
                Filename = Filename & ".icr"
    
                IceCreamReader = My.Computer.FileSystem.OpenTextFileReader(Filename)
    
                ' Find out if this order was previously saved in the machine
                If My.Computer.FileSystem.FileExists(Filename) Then
                    ' If so, open it
                    OrderDate = IceCreamReader.ReadLine()
                    OrderTime = IceCreamReader.ReadLine()
                    SelectedFlavor = IceCreamReader.ReadLine()
                    SelectedContainer = IceCreamReader.ReadLine()
                    SelectedIngredient = IceCreamReader.ReadLine()
                    Scoops = IceCreamReader.ReadLine()
                    OrderTotal = IceCreamReader.ReadLine()
    
                    ' And display it to the user
                    dtpOrderDate.Value = DateTime.Parse(OrderDate)
                    dtpOrderTime.Value = DateTime.Parse(OrderTime)
                    cboFlavors.Text = SelectedFlavor
                    cboContainers.Text = SelectedContainer
                    cboIngredients.Text = SelectedIngredient
                    txtScoops.Text = Scoops.ToString()
                    txtOrderTotal.Text = OrderTotal
    
                    IceCreamReader.Close()
                Else
                    MsgBox("It looks like you have not previously " & _
                                 "ordered an ice cream here")
                End If
            End If
    End Sub
  3. Execute the application and test it. Here is an example:
     
    Microsoft Visual Basic Input Box
    Clarksville Ice Cream
  4. Close the form
 

Previous  Copyright © 2008-2016, FunctionX, Inc. Home