Home

Binary File Streaming

 

Introduction to File Streaming

File streaming consists of performing one of the routine operations on a file, such as creating or opening it. This basic operation can be performed using a class called FileStream. You can use a FileStream object to get a stream ready for processing. As one of the most complete classes of file processing of the .NET Framework, FileStream is equipped with all necessary properties and methods. To use it, you must first declare a variable of it. The class is equipped with nine constructors.

One of the constructors (the second) of the FileStream class has the following syntax:

Public Sub New(ByVal path As String, ByVal mode As FileMode)

This constructor takes as its first argument the name of the file or its path. The second argument specifies the type of operation to perform on the file. Here is an example:

Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
			Handles btnStart.Click
        Dim fileName As String = "Persons.spr"

        Dim fstPersons As FileStream = New FileStream(fileName, FileMode.Create)
End Sub
 

Practical LearningPractical Learning: Introducing File Streaming

  1. Create a new Windows Forms Application named ROSH1
  2. Design the form as follows:
     
    Red Oak High School - Form Design
    Control Name Text Other Properties
    GroupBox GroupBox   Identification  
    Label   Student Name:  
    TextBox txtStudentName    
    Label   School Year:  
    TextBox txtSchoolYear1    
    Label   /  
    TextBox txtSchoolYear2    
    GroupBox   Grades  
    Label   English:  
    TextBox txtEnglish 0.00  
    Label   History:  
    TextBox txtHistory 0.00  
    Label   Economics:  
    TextBox txtEconomics 0.00  
    Label   2nd Language:  
    TextBox txt2ndLanguage 0.00  
    Label   Geography:  
    TextBox txtGeography 0.00  
    Label   Arts:  
    TextBox txtArts 0.00  
    Label   Math:  
    TextBox txtMath 0.00  
    Label   Science:  
    TextBox txtScience 0.00  
    Label   Phys Educ:  
    TextBox txtPhysEduc 0.00  
    GroupBox   Grade Processing  
    Button btnCalculate Calculate  
    Label   Total:  
    TextBox txtTotal 0.00  
    Label   Average:  
    TextBox txtAverage 0.00  
    Button btnSave Save  
    Button btnOpen Open  
    Button btnClose Close  
  3. Double-click the Calculate button and implement its Click event as follows:
     
    Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    			Handles btnCalculate.Click
            Dim english As Double
            Dim history As Double
            Dim economics As Double
            Dim language2 As Double
            Dim geography As Double
            Dim arts As Double
            Dim math As Double
            Dim science As Double
            Dim physEduc As Double
            Dim total As Double
            Dim average As Double
    
            ' Retrieve the value entered for each course
            Try
                english = CDbl(Me.txtEnglish.Text)
            Catch ex As FormatException
                MsgBox("The value you entered for the English course is not valid")
                Me.txtEnglish.Focus()
            End Try
    
            Try
                history = CDbl(Me.txtHistory.Text)
            Catch ex As FormatException
                MsgBox("The value you entered for the History course is not valid")
                Me.txtEnglish.Focus()
            End Try
    
            Try
                economics = CDbl(Me.txtEconomics.Text)
            Catch ex As FormatException
                MsgBox("The value you entered for the Economics course is not valid")
                Me.txtEnglish.Focus()
            End Try
    
            Try
                language2 = CDbl(Me.txt2ndLanguage.Text)
            Catch ex As FormatException
                MsgBox("The value you entered for the 2nd Language course is not valid")
                Me.txtEnglish.Focus()
            End Try
    
            Try
                geography = CDbl(Me.txtGeography.Text)
            Catch ex As FormatException
                MsgBox("The value you entered for the Geography course is not valid")
                Me.txtEnglish.Focus()
            End Try
    
            Try
                arts = CDbl(Me.txtArts.Text)
            Catch ex As FormatException
                MsgBox("The value you entered for the Arts course is not valid")
                Me.txtEnglish.Focus()
            End Try
    
            Try
                math = CDbl(Me.txtMath.Text)
            Catch ex As FormatException
                MsgBox("The value you entered for the Math course is not valid")
                Me.txtEnglish.Focus()
            End Try
    
            Try
                science = CDbl(Me.txtScience.Text)
            Catch ex As FormatException
                MsgBox("The value you entered for the Science course is not valid")
                Me.txtEnglish.Focus()
            End Try
    
            Try
                physEduc = CDbl(Me.txtPhysEduc.Text)
            Catch ex As FormatException
                MsgBox("The value you entered for the Physical Education course is not valid")
                Me.txtEnglish.Focus()
            End Try
    
            ' Calculate the total and the average
            total = english + history + economics + language2 + _
                  geography + arts + math + science + physEduc
            average = total / 9
    
            ' Display the total and the average
            Me.txtTotal.Text = total.ToString("F")
            Me.txtAverage.Text = average.ToString("F")
    End Sub
  4. Return to the form.
    Double-click the Close button and implement its event as follows:
     
    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    			Handles btnClose.Click
            Close()
    End Sub
  5. Execute the application to test it
 

Stream Writing

A streaming operation is typically used to create a stream. Once the stream is ready, you can write data to it. The writing operation is performed through various classes. One of these classes is BinaryWriter.

The BinaryWriter class can be used to write values of primitive data types (char, int, float, double, etc). To use a BinaryWriter value, you can first declare its pointer. To do this, you would use one of the class' three constructors. The first constructor is the default, meaning it doesn't take an argument. The second constructor has the following syntax:

Public Sub New(ByVal output As Stream)

This constructor takes as argument a Stream value, which could be a FileStream variable. Here is an example:

Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim fileName As String = "Persons.spr"

        Dim fstPersons As FileStream = New FileStream(fileName, FileMode.Create)
        Dim wrtPersons As BinaryWriter = New BinaryWriter(fstPersons)
End Sub

Most classes that are used to add values to a stream are equipped with a method called Write. This is also the case for the BinaryWriter class. This method takes as argument the value that must be written to the stream. The method is overloaded so that there is a version for each primitive data type. Here is an example that adds strings to a newly created file:

Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim fileName As String = "Persons.spr"

        Dim fstPersons As FileStream = New FileStream(fileName, FileMode.Create)
        Dim wrtPersons As BinaryWriter = New BinaryWriter(fstPersons)

        wrtPersons.Write("James Bloch")
        wrtPersons.Write("Catherina Wallace")
        wrtPersons.Write("Bruce Lamont")
        wrtPersons.Write("Douglas Truth")
End Sub

Stream Closing

When you use a stream, it requests resources from the operating system and uses them while the stream is available. When you are not using the stream anymore, you should free the resources and make them available again to the operating system so that other services can use them. This is done by closing the stream.

To close a stream, you can can call the Close() method of the class(es) you were using. Here are examples:

Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim fileName As String = "Persons.spr"

        Dim fstPersons As FileStream = New FileStream(fileName, FileMode.Create)
        Dim wrtPersons As BinaryWriter = New BinaryWriter(fstPersons)

        wrtPersons.Write("James Bloch")
        wrtPersons.Write("Catherina Wallace")
        wrtPersons.Write("Bruce Lamont")
        wrtPersons.Write("Douglas Truth")

        wrtPersons.Close()
        fstPersons.Close()
End Sub

Practical LearningPractical Learning: Writing to a Stream

  1. Right-click the form and click View Code
  2. In the top section of the file, type Imports System.IO as the first line of the file
     
  3. Display the form
    In the Toolbox, click the SaveFileDialog button SaveFileDialog and click the form
  4. In the Properties window, change the following properties
    DefaultExt: ros
    Filter: ROSH Students Grades (.ros)|.ros|All Files(.)|
    Title: Save Student Grades As
  5. On the form, double-click the Save button and implement its Click event as follows:
     
    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    			Handles btnSave.Click
            Dim stmGrades As FileStream
            Dim bnwGrades As BinaryWriter
    
            ' The information will not be saved if there is no name for the student
            If Me.txtStudentName.Text = "" Then
                MsgBox("The report cannot be saved without the name of the student")
                Me.txtStudentName.Focus()
                Exit Sub
            End If
    
            ' The information will not be saved if there is no school year
            If Me.txtSchoolYear1.Text = "" Then
                MsgBox("The report cannot be saved without the school year")
                Me.txtSchoolYear1.Focus()
                Exit Sub
            End If
    
            If Me.txtSchoolYear2.Text = "" Then
                MsgBox("The report cannot be saved without the school year")
                Me.txtSchoolYear2.Focus()
                Exit Sub
            End If
    
            Dim strFilename As String
    
            strFilename = Me.txtStudentName.Text + Me.txtSchoolYear1.Text + Me.txtSchoolYear2.Text
            Me.saveFileDialog1.FileName = strFilename
            ' Display the Save dialog box
            ' Find out if the user clicked OK or pressed Enter
            If Me.saveFileDialog1.ShowDialog() = DialogResult.OK Then
                ' If the used provided a name that already exists for an existing file
                If File.Exists(Me.saveFileDialog1.FileName) Then
                    ' Find out if the user wants to replace the existing file
                    Dim answer As System.Windows.Forms.DialogResult = _
                            MessageBox.Show("The student report exists already." + _
                                            "Do you want to replace it?", _
                                            "Save Student Report", _
                                            MessageBoxButtons.YesNo)
    
                    ' If the user wants to replace it
                    If answer = DialogResult.Yes Then
                        stmGrades = New FileStream(Me.saveFileDialog1.FileName, FileMode.Create)
                        bnwGrades = New BinaryWriter(stmGrades)
    
                        ' Then overwrite it
                        bnwGrades.Write(Me.txtStudentName.Text)
                        bnwGrades.Write(Me.txtSchoolYear1.Text)
                        bnwGrades.Write(Me.txtSchoolYear2.Text)
                        bnwGrades.Write(CDbl(Me.txtEnglish.Text))
                        bnwGrades.Write(CDbl(Me.txtHistory.Text))
                        bnwGrades.Write(CDbl(Me.txtEconomics.Text))
                        bnwGrades.Write(CDbl(Me.txt2ndLanguage.Text))
                        bnwGrades.Write(CDbl(Me.txtGeography.Text))
                        bnwGrades.Write(CDbl(Me.txtArts.Text))
                        bnwGrades.Write(CDbl(Me.txtMath.Text))
                        bnwGrades.Write(CDbl(Me.txtScience.Text))
                        bnwGrades.Write(CDbl(Me.txtPhysEduc.Text))
    
                        bnwGrades.Close()
                        stmGrades.Close()
                    Else
                        stmGrades = New FileStream(Me.saveFileDialog1.FileName, FileMode.Create)
                        bnwGrades = New BinaryWriter(stmGrades)
    
                        bnwGrades.Write(Me.txtStudentName.Text)
                        bnwGrades.Write(Me.txtSchoolYear1.Text)
                        bnwGrades.Write(Me.txtSchoolYear2.Text)
                        bnwGrades.Write(CDbl(Me.txtEnglish.Text))
                        bnwGrades.Write(CDbl(Me.txtHistory.Text))
                        bnwGrades.Write(CDbl(Me.txtEconomics.Text))
                        bnwGrades.Write(CDbl(Me.txt2ndLanguage.Text))
                        bnwGrades.Write(CDbl(Me.txtGeography.Text))
                        bnwGrades.Write(CDbl(Me.txtArts.Text))
                        bnwGrades.Write(CDbl(Me.txtMath.Text))
                        bnwGrades.Write(CDbl(Me.txtScience.Text))
                        bnwGrades.Write(CDbl(Me.txtPhysEduc.Text))
    
                        bnwGrades.Close()
                        stmGrades.Close()
                    End If
                End If
            End If
        End Sub
  6. Execute the application and create a record:
     
  7. Save the record and close the form

Stream 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 btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim fileName As String = "Persons.spr"

        '        Dim fstPersons As FileStream = New FileStream(fileName, FileMode.Create)
        '       Dim wrtPersons As BinaryWriter = New BinaryWriter(fstPersons)

        '      wrtPersons.Write("James Bloch")
        '     wrtPersons.Write("Catherina Wallace")
        '    wrtPersons.Write("Bruce Lamont")
        '   wrtPersons.Write("Douglas Truth")
        '
        '     wrtPersons.Close()
        '    fstPersons.Close()

        Dim fstPersons As New FileStream(fileName, FileMode.Open)
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(ByVal 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 btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim fileName As String = "Persons.spr"

        '       Dim fstPersons As FileStream = New FileStream(fileName, FileMode.Create)
        '       Dim wrtPersons As BinaryWriter = New BinaryWriter(fstPersons)

        '      wrtPersons.Write("James Bloch")
        '      wrtPersons.Write("Catherina Wallace")
        '      wrtPersons.Write("Bruce Lamont")
        '      wrtPersons.Write("Douglas Truth")
        '
        '     wrtPersons.Close()
        '     fstPersons.Close()

        Dim fstPersons As New FileStream(fileName, FileMode.Open)
        Dim rdrPersons As New BinaryReader(fstPersons)

        rdrPersons.Close()
        fstPersons.Close()
End Sub

Practical LearningPractical Learning: Reading From a Stream

  1. In the Toolbox, click the OpenFileDialog button SaveFileDialog and click the form
  2. In the Properties window, change the following properties
    DefaultExt: ros
    Filter: ROSH Students Grades (.ros)|.ros|All Files(.)|
    Title: Open Student Grades
  3. On the form, double-click the Save button and implement its Click event as follows:
     
    Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    			Handles btnOpen.Click
            ' Display the Open dialog box
            ' Find out if the user selected a file and clicked OK
            If Me.openFileDialog1.ShowDialog() = DialogResult.OK Then
                Dim stmGrades As New FileStream(Me.openFileDialog1.FileName, FileMode.Open)
                Dim bnrGrades As New BinaryReader(stmGrades)
    
                If File.Exists(Me.openFileDialog1.FileName) Then
                    ' Retrieve the values from the file
                    Me.txtStudentName.Text = bnrGrades.ReadString()
                    Me.txtSchoolYear1.Text = bnrGrades.ReadString()
                    Me.txtSchoolYear2.Text = bnrGrades.ReadString()
                    Me.txtEnglish.Text = bnrGrades.ReadDouble().ToString("F")
                    Me.txtHistory.Text = bnrGrades.ReadDouble().ToString("F")
                    Me.txtEconomics.Text = bnrGrades.ReadDouble().ToString("F")
                    Me.txt2ndLanguage.Text = bnrGrades.ReadDouble().ToString("F")
                    Me.txtGeography.Text = bnrGrades.ReadDouble().ToString("F")
                    Me.txtArts.Text = bnrGrades.ReadDouble().ToString("F")
                    Me.txtMath.Text = bnrGrades.ReadDouble().ToString("F")
                    Me.txtScience.Text = bnrGrades.ReadDouble().ToString("F")
                    Me.txtPhysEduc.Text = bnrGrades.ReadDouble().ToString("F")
    
                    ' Close the stream
                    bnrGrades.Close()
                    stmGrades.Close()
    
                    ' Since we didn't save the results of the calculations,
                    ' call the Calculate button to do it
                    Me.btnCalculate_Click(sender, e)
                End If
            End If
    End Sub
  4. Execute the application and open the previously saved record
 
Previous Copyright © 2004-2010 FunctionX, Inc. Next