Home

File Processing: Writing to a Stream

   

Binary 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 called 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 variable. To do this, you would use one of the class' three constructors. The first constructor is the default. The second constructor has the following syntax:

Public Sub New(output As Stream)

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

Public Class Exercise

    Private Sub btnSave_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles btnSave.Click
        Dim Filename As String = "Persons.prs"

        Dim StreamPersons As FileStream = New FileStream(Filename, FileMode.Create)
        Dim WriterPersons As BinaryWriter  = new BinaryWriter(fstPersons)
   
    End Sub
End Class

As mentioned already, make sure you close a stream after using it. In the same way, make sure you close a writer after using it. If you are using both, you should close them in the reverse order they were used.

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:

Persons

Imports System.IO

Public Class Exercise

    Private Sub btnSave_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles btnSave.Click
        Dim Filename As String = "Persons.prs"

        Dim PersonsStream As FileStream
        Dim PersonsWriter As BinaryWriter

        PersonsStream = New FileStream(Filename, FileMode.Create)
        PersonsWriter = New BinaryWriter(PersonsStream)

        PersonsWriter.Write(txtPerson1.Text)
        PersonsWriter.Write(txtPerson2.Text)
        PersonsWriter.Write(txtPerson3.Text)
        PersonsWriter.Write(txtPerson4.Text)

        PersonsWriter.Close()
        PersonsStream.Close()

        txtPerson1.Text = ""
        txtPerson2.Text = ""
        txtPerson3.Text = ""
        txtPerson4.Text = ""
    End Sub
End Class

Stream Writing

As mentioned already, the BinaryWriter class considers the values it has to write as binary values in the orders of integers, characters, and their variants. In some cases, you may want to write a block of text. To support this, the .NET Framework provides the StreamWriter class. StreamWriter is derived from the TextWriter class, which the base class used to write a series of characters to a stream. To assist you with writing operations, the StramWriter class is equipped with various constructors.

If you had previously defined a FileStream object and you want to write values to it, you can use the following constructor of the StreamWriter 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. Here is an example of using it:

Imports System.IO

Public Class StudentRegistration

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

        Dim StudentsStreamer As FileStream
        Dim StudentsWriter As StreamWriter

        StudentsStreamer = New FileStream(Filename, FileMode.Create)
        StudentsWriter = New StreamWriter(StudentsStreamer)
    End Sub
End Class

If you do not want to use a Stream-based class, you can directly provide a file to the StreamWriter. To support this, the class is equipped with the following constructor:

Public Sub New(path As String)

This method takes as argument the name of, or a path to, a file.

After creating a StreamWriter object, you can write one or more values to it. To support this, the TextWriter class is equipped with the Write() method that the StreamWriter class inherits. The StreamWriter class itself is equipped is equipped with w method named WriteLine that is given in various versions, each version adapted to a particular data type. The Write() method writes text on a line and keeps the caret on the same line. The WriteLine() method writes a line of text and moves the caret to the next line.

Here is an example of using a StreamWriter class to write values to a file:

After creating a StreamWriter object, you can write one or more values to it. To support this, the TextWriter class is equipped with the Write() method that the StreamWriter class inherits. The StreamWriter class itself is equipped is equipped with w method named WriteLine that is given in various versions, each version adapted to a particular data type.

Imports System.IO

Public Class StudentRegistration

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

        Dim StudentsStreamer As FileStream
        Dim StudentsWriter As StreamWriter

        StudentsStreamer = New FileStream(Filename, FileMode.Create)
        StudentsWriter = New StreamWriter(StudentsStreamer)

        StudentsWriter.WriteLine(txtFirstName.Text)
        StudentsWriter.WriteLine(txtLastName.Text)
        StudentsWriter.WriteLine(cbxGenders.SelectedIndex)

        StudentsWriter.Close()
        StudentsStreamer.Close()

        txtFirstName.Text = ""
        txtLastName.Text = ""
        cbxGenders.SelectedIndex = 2
    End Sub
End Class

Using My File System

By default, the FileStream class does not specify what operation is going to be performed on the file. If you are planning to create a new file and write values to it, you can call the OpenTextFileWriter() method of the FileSystem class of the My object. It comes in two versions whose syntaxes are:

Public Function OpenTextFileWriter( _
   ByVal file As String, _
   ByVal append As Boolean _
) As System.IO.StreamWriter

Public Function OpenTextFileWriter( _
   ByVal file As String, _
   ByVal append As Boolean, _
   ByVal encoding As System.Text.Encoding _
) As System.IO.StreamWriter

The first argument is the name of, or the path to, the file that will receive the new values. The second argument specifies whether this is a new file or you are opening it to add new values to it. If this is a new file, pass the append argument as False. The encoding argument allows you to specify the type of text that you want to use.

This method returns a StreamWriter. Here is an example of creating a stream writer by calling the OpenTextFileWriter() method:

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, _
			ByVal e As System.EventArgs) _
			Handles Button1.Click
        Dim fstPeople As StreamWriter

        fstPeople = My.Computer.FileSystem.OpenTextFileWriter("People1.ppl", False)

    End Sub
End Class

After creating the stream writer, you can then write values to it. To do this, you can call the WriteLine() method of the StreamWriter class. Once again, after using the stream writer, remember to close it. Here are examples:

Imports System.IO

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, _
		ByVal e As System.EventArgs) _
		Handles Button1.Click
        Dim fstPeople As StreamWriter

        fstPeople = My.Computer.FileSystem.OpenTextFileWriter("People1.ppl", False)

        fstPeople.WriteLine(txtPerson1.Text)
        fstPeople.WriteLine(txtPerson2.Text)
        fstPeople.WriteLine(txtPerson3.Text)
        fstPeople.WriteLine(txtPerson4.Text)
        fstPeople.Close()

        txtPerson1.Text = ""
        txtPerson2.Text = ""
        txtPerson3.Text = ""
        txtPerson4.Text = ""
    End Sub
End Class

Practical LearningPractical Learning: Writing to a Stream

  1. Scroll back down the file and change the code of the btnClose_Click event as follows:
     
    Private Sub btnClose_Click(ByVal sender As Object, _
                                   ByVal e As System.EventArgs) _
                                   Handles btnClose.Click
            Dim Filename As String
            Dim Answer As MsgBoxResult
            Dim IceCreamWriter As StreamWriter
    
            Answer = MsgBox("Do you want to save this order to remember it " & _
                            "the next time you come to " & _
                            "get your ice cream?", _
                            MsgBoxStyle.YesNo Or MsgBoxStyle.Question, _
                            "Ice Cream Vending Machine")
        If Answer = MsgBoxResult.Yes Then
                Filename = InputBox( _
                    "Please type your initials and press Enter", _
                    "Ice Cream Vending Machine", "AA", 100, 100)
            If Filename <> "" Then
                Filename = Filename & ".icr"
    
                IceCreamWriter = _
    		My.Computer.FileSystem.OpenTextFileWriter(Filename, False)
                    
                IceCreamWriter.WriteLine(dtpOrderDate.Value.ToShortDateString())
                IceCreamWriter.WriteLine(dtpOrderTime.Value.ToShortTimeString())
                IceCreamWriter.WriteLine(cboFlavors.Text)
                IceCreamWriter.WriteLine(cboContainers.Text)
                IceCreamWriter.WriteLine(cboIngredients.Text)
                IceCreamWriter.WriteLine(txtScoops.Text)
                IceCreamWriter.WriteLine(txtOrderTotal.Text)
    
                IceCreamWriter.Close()
    
                    MsgBox("The order has been saved")
                Else
                    MsgBox("The ice cream order will not be saved")
                End If
            End If
    
            MsgBox("Good Bye: It was a delight serving you")
            Close()
    End Sub
  2. Execute the application and create an ice cream order. Here is an example:
     
    Clarksville Ice Cream
    Clarksville Ice Cream
    Clarksville Ice Cream
    Clarksville Ice Cream
  3. Close the form and return to your programming environment
 

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