Home

File Streams

 

Fundamental File Streaming

 

Introduction to File Streaming

File streaming consists of performing one of the routine operations on a file, such as creating it 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 or the file or its path. The second argument specifies the type of operation to perform on the file. Here is an example:

Imports System
Imports System.IO

Public Class Exercise
    Public Shared Sub main()
        Dim NameOfFile As String = "Persons.spr"

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

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 perform 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 variable. To do this, you would use one of the class' three constructors. One of its constructors (the second) 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:

Imports System
Imports System.IO

Public Class Exercise
    Public Shared Sub main()
        Dim NameOfFile As String = "Persons.spr"

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

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:

Imports System
Imports System.IO

Public Class Exercise
    Public Shared Sub main()
        Dim NameOfFile As String = "Persons.spr"

        Dim fstPersons As FileStream = New FileStream(NameOfFile, 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
End Class

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:

Imports System
Imports System.IO

Public Class Exercise
    Public Shared Sub main()
        Dim NameOfFile As String = "Persons.spr"

        Dim fstPersons As FileStream = New FileStream(NameOfFile, 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
End Class

Practical Learning: Writing to a Stream

  1. To be able to complete a file, change the Save() method in the IceCream.vb file as follows:
     
    Public Sub Save()
            Dim NameOfFile As String
    
            Console.WriteLine("Please enter your initials or the name " & _
    			  "we will use to remember your order: ")
            NameOfFile = Console.ReadLine()
            NameOfFile = NameOfFile & ".icr"
    
            ' Find out if the user entered a name of a file that " & _
    			  "is already in the machine
            If File.Exists(NameOfFile) Then
                Dim Answer As String
    
                Dim stmIceCream As FileStream = _
    		New FileStream(NameOfFile, FileMode.Create)
                Dim bnwIceCream As BinaryWriter = New BinaryWriter(stmIceCream)
    
                ' If so, find out if the user wants to replace the old file
                Console.WriteLine("The file you entered exists already.")
                Console.Write("Do you want to replace it(y/n)?")
                Answer = Console.ReadLine()
    
                ' If the customer wants to replace it...
                If Answer = "y" Or Answer = "Y" Then
    
                    ' ... do so
                    Console.WriteLine("The former order with the " & _
    			  "same name will be replaced")
    
                    Console.WriteLine(vbCrLf & "=-= Ice Cream Vending Machine =-=")
                    Console.WriteLine(" Saving Order: {0}", NameOfFile)
                    bnwIceCream.Write(Flavors(ChoiceFlavor))
                    bnwIceCream.Write(Containers(ChoiceContainer))
                    bnwIceCream.Write(Ingredients(ChoiceIngredient))
                    bnwIceCream.Write(Scoops)
                    bnwIceCream.Write(TotalPrice)
    
                    ' If the customer wants to save the new order with a different name
                ElseIf Answer = "n" Or Answer = "N" Then
                    ' Ask the user to enter a name to remember the order
                    Console.Write("Please enter a name we will " & _
    			  "use to remember this order: ")
                    NameOfFile = Console.ReadLine()
                    NameOfFile = NameOfFile & ".icr"
    
                    stmIceCream = New FileStream(NameOfFile, FileMode.Create)
                    bnwIceCream = New BinaryWriter(stmIceCream)
    
                    Console.WriteLine(vbCrLf & "=-= Ice Cream Vending Machine =-=")
                    Console.WriteLine(" Saving Order: {0}", NameOfFile)
                    bnwIceCream.Write(Flavors(ChoiceFlavor))
                    bnwIceCream.Write(Containers(ChoiceContainer))
                    bnwIceCream.Write(Ingredients(ChoiceIngredient))
                    bnwIceCream.Write(Scoops)
                    bnwIceCream.Write(TotalPrice)
                Else
                    Console.WriteLine("Invalid Answer - We will close")
                    bnwIceCream.Close()
                    stmIceCream.Close()
                End If
            Else
    
                Dim stmIceCream As FileStream = _
    		New FileStream(NameOfFile, FileMode.Create)
                Dim bnwIceCream As BinaryWriter = New BinaryWriter(stmIceCream)
    
                Console.WriteLine(vbCrLf & "=-= Ice Cream Vending Machine =-=")
                Console.WriteLine(" Saving Order: {0}", NameOfFile)
                bnwIceCream.Write(Flavors(ChoiceFlavor))
                bnwIceCream.Write(Containers(ChoiceContainer))
                bnwIceCream.Write(Ingredients(ChoiceIngredient))
                bnwIceCream.Write(Scoops)
                bnwIceCream.Write(TotalPrice)
    
                bnwIceCream.Close()
                stmIceCream.Close()
            End If
        End Sub
  2. Save the file and switch to the Command Prompt
  3. To compile it, type vbc /out:"Ice Cream Vending Machine".exe IceCream.vb Exercise.vb and press Enter
  4. To execute it, type "Ice Cream Vending Machine" and press Enter. Here is an example:
     
    Have you ordered here before(y/n)? n
    
    =-= Ice Cream Vending Machine =-=
     ------ New Customer Order ------
    What type of flavor do you want?
    1 - Vanilla
    2 - Cream of Cocoa
    3 - Chocolate Chip
    4 - Organic Strawberry
    5 - Butter Pecan
    6 - Cherry Coke
    7 - Chocolate Brownies
    8 - Caramel Au Lait
    9 - Chunky Butter
    10 - Chocolate Cookie
    Your Choice? 7
    What type of container do you want?
    1 - Cone
    2 - Cup
    3 - Bowl
    Your Choice? 1
    Do you want an ingredient or not
    1 - No Ingredient
    2 - Peanuts
    3 - M & M
    4 - Cookies
    Your Choice? 4
    How many scoops(1, 2, or 3)? 2
    
    Ice Cream Order
    Flavor:      Chocolate Brownies
    Container:   Cone
    Ingredient:  Cookies
    Scoops:      2
    Total Price: $3.10
    
    Do you want us to remember this order the next 
    time you come to get your ice scream (y/n)? y
    Please enter your initials or the name we will use to remember your order:
    Jane44
    
    =-= Ice Cream Vending Machine =-=
     Saving Order: Jane44.icr
  5. Return to the IceCream.vb file
 

 

 

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:

Imports System
Imports System.IO

Public Class Exercise
    Public Shared Sub main()
        Dim NameOfFile As String = "Persons.spr"

        Dim fstPersons As FileStream = New FileStream(NameOfFile, FileMode.Open)

    End Sub
End Class

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 do this, you can call an appropriate method. This 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:

Imports System
Imports System.IO

Public Class Exercise
    Public Shared Sub main()
        Dim NameOfFile As String = "Persons.spr"

        Dim fstPersons As FileStream = New FileStream(NameOfFile, FileMode.Open)
        Dim rdrPersons As BinaryReader = New BinaryReader(fstPersons)
        Dim strLine As String

        strLine = rdrPersons.ReadString()
        Console.WriteLine(strLine)
        strLine = rdrPersons.ReadString()
        Console.WriteLine(strLine)
        strLine = rdrPersons.ReadString()
        Console.WriteLine(strLine)
        strLine = rdrPersons.ReadString()
        Console.WriteLine(strLine)

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

This would produce:

James Bloch
Catherina Wallace
Bruce Lamont
Douglas Truth

Practical LearningPractical Learning: Reading From a Stream

  1. To be able to retrieve data from an existing file, change the OpenFile() method as follows:
     
    Source File: IceCream.vb
    Imports System
    Imports System.IO
    
    ' This class is used to create and manage an ice cream
    ' and to process an order
    Public NotInheritable Class IceCream
        ' This is the base price of an ice cream
        ' Optional values may be added to it
        Public Const BasePrice As Double = 1.55
    
        ' These arrays are used to build the components of various ice creams
        ' In C#, we can allocate an array's memory in the body of the class
        Private Flavors As Collection
        Private Containers As Collection
        Private Ingredients As Collection
    
        ' Additional factor used to process an ice cream order
        Private Scoops As Integer
        Private TotalPrice As Double
    
        ' Variables that will hold the user's choice
        ' These are declared "globally" so they can be shared among methods
        Dim ChoiceFlavor As Integer
        Dim ChoiceContainer As Integer
        Dim ChoiceIngredient As Integer
    
        ' This default constructor is the best place 
        ' for us to initialize the array
        Public Sub New()
            Flavors = New Collection
            Flavors.Add("Vanilla")
            Flavors.Add("Cream of Cocoa")
            Flavors.Add("Chocolate Chip")
            Flavors.Add("Organic Strawberry")
            Flavors.Add("Butter Pecan")
            Flavors.Add("Cherry Coke")
            Flavors.Add("Chocolate Brownies")
            Flavors.Add("Caramel Au Lait")
            Flavors.Add("Chunky Butter")
            Flavors.Add("Chocolate Cookie")
    
            Ingredients = New Collection
            Ingredients.Add("No Ingredient")
            Ingredients.Add("Peanuts")
            Ingredients.Add("M & M")
            Ingredients.Add("Cookies")
    
            Containers = New Collection
            Containers.Add("Cone")
            Containers.Add("Cup")
            Containers.Add("Bowl")
        End Sub
    
        ' This method requests a flavor from the user and returns the choice
        Public Sub ChooseFlavor()
            ' Make sure the user selects a valid number that represents a flavor...
            Do
                ' In case the user types a symbol that is not a number
                Try
                    Console.WriteLine("What type of flavor do you want?")
                    For i As Integer = 1 To Flavors.Count Step 1
                        Console.WriteLine("{0} - {1}", i, Flavors(i))
                    Next
                    Console.Write("Your Choice? ")
                    ChoiceFlavor = CInt(Console.ReadLine())
                Catch ex As InvalidCastException ' display an appropriate message
                    Console.WriteLine("You must enter a valid " & _
    			  "number and no other character!")
                End Try
    
                ' If the user typed an invalid number out of the allowed range
                ' let him or her know and provide another chance
                If ChoiceFlavor < 1 Or ChoiceFlavor > Flavors.Count Then
                    Console.WriteLine("Invalid Choice - Try Again!" & vbCrLf)
                End If
            Loop While ChoiceFlavor < 1 Or ChoiceFlavor > Flavors.Count
        End Sub
    
        ' This method allows the user to select a container
        Public Sub ChooseContainer()
            ' Make sure the user selects a valid number that represents a container
            Do
                ' If the user types a symbol that is not a number
                Try
                    Console.WriteLine("What type of container do you want?")
                    For i As Integer = 1 To Containers.Count Step 1
                        Console.WriteLine("{0} - {1}", i, Containers(i))
                    Next
                    Console.Write("Your Choice? ")
                    ChoiceContainer = CInt(Console.ReadLine())
                Catch ex As InvalidCastException
                    Console.WriteLine("You must enter a valid " & _
    			  "number and no other character!")
                End Try
    
                ' If the user typed an invalid number out of the allowed range
                ' let him or her know and provide another chance
                If ChoiceContainer < 1 Or ChoiceContainer > Containers.Count Then
                    Console.WriteLine("Invalid Choice - Try Again!")
                End If
            Loop While ChoiceContainer < 1 Or ChoiceContainer > Containers.Count
        End Sub
    
        Public Sub ChooseIngredient()
            Do
                Try
                    Console.WriteLine("Do you want an ingredient or not")
                    For i As Integer = 1 To Ingredients.Count Step 1
                        Console.WriteLine("{0} - {1}", i, Ingredients(i))
                    Next
                    Console.Write("Your Choice? ")
                    ChoiceIngredient = CInt(Console.ReadLine())
                Catch ex As InvalidCastException
                    Console.WriteLine("You must enter a valid " & _
    			  "number and no other character!")
                End Try
    
                If ChoiceIngredient < 1 Or ChoiceIngredient > Ingredients.Count Then
                    Console.WriteLine("Invalid Choice - Try Again!")
                End If
            Loop While ChoiceIngredient < 1 Or ChoiceIngredient > Ingredients.Count
        End Sub
    
        Public Sub SpecifyNumberOfScoops()
            Do
                Try
                    Console.Write("How many scoops(1, 2, or 3)? ")
                    Scoops = CInt(Console.ReadLine())
                Catch ex As InvalidCastException
                    Console.WriteLine("You must enter a valid " & _
    			  "number and no other character!")
                End Try
    
                If Scoops < 1 Or Scoops > 3 Then
                    Console.WriteLine("Invalid Choice - Try Again!")
                End If
            Loop While Scoops < 1 Or Scoops > 3
        End Sub
    
        ' This method is used to process a customer order
        ' It uses the values of the above methods
        Public Sub ProcessAnOrder()
            Dim PriceIngredient As Double
            Dim PriceScoop As Double
    
            ' Let the user know that this is a vending machine
            Console.WriteLine("Ice Cream Vending Machine")
    
            ' Let the user select the components of the ice cream
            ChooseFlavor()
            ChooseContainer()
            ChooseIngredient()
            SpecifyNumberOfScoops()
    
            ' If the user selects an ingredient instead of "No Ingredient",
            ' add $0.50 to the order
            If ChoiceIngredient = 2 Or _
    	   ChoiceIngredient = 3 Or _
    	   ChoiceIngredient = 4 Then
                PriceIngredient = 0.5
            Else
                PriceIngredient = 0.0
            End If
    
            ' Instead of multiplying a number scoops to a value,
            ' We will use an incremental value depending on the number of scoops
            If Scoops = 1 Then
                PriceScoop = 0.65
            ElseIf Scoops = 2 Then
                PriceScoop = 1.05
            Else
                PriceScoop = 1.55
            End If
    
            ' Calculate the total price of the ice cream
            TotalPrice = BasePrice + PriceScoop + PriceIngredient
    
            ' Create the ice cream...
    
            ' And display a receipt to the user
            DisplayReceipt()
        End Sub
    
        ' This method is used to display a receipt to the user
        Public Sub DisplayReceipt()
            Console.WriteLine(vbCrLf & "Ice Cream Order")
            Console.WriteLine("Flavor:      {0}", Flavors(ChoiceFlavor))
            Console.WriteLine("Container:   {0}", Containers(ChoiceContainer))
            Console.WriteLine("Ingredient:  {0}", Ingredients(ChoiceIngredient))
            Console.WriteLine("Scoops:      {0}", Scoops)
            Console.WriteLine("Total Price: {0:C}" & vbCrLf, TotalPrice)
        End Sub
    
        Public Sub Save()
            Dim NameOfFile As String
    
            Console.WriteLine("Please enter your initials or the name " & _
    			  "we will use to remember your order: ")
            NameOfFile = Console.ReadLine()
            NameOfFile = NameOfFile & ".icr"
    
            ' Find out if the user entered a name of a 
    	' file that is already in the machine
            If File.Exists(NameOfFile) Then
                Dim Answer As String
    
                Dim stmIceCream As FileStream = _
    		New FileStream(NameOfFile, FileMode.Create)
                Dim bnwIceCream As BinaryWriter = New BinaryWriter(stmIceCream)
    
                ' If so, find out if the user wants to replace the old file
                Console.WriteLine("The file you entered exists already.")
                Console.Write("Do you want to replace it(y/n)?")
                Answer = Console.ReadLine()
    
                ' If the customer wants to replace it...
                If Answer = "y" Or Answer = "Y" Then
    
                    ' ... do so
                    Console.WriteLine("The former order with the " & _
    			  "same name will be replaced")
    
                    Console.WriteLine(vbCrLf & "=-= Ice Cream Vending Machine =-=")
                    Console.WriteLine(" Saving Order: {0}", NameOfFile)
                    bnwIceCream.Write(Flavors(ChoiceFlavor))
                    bnwIceCream.Write(Containers(ChoiceContainer))
                    bnwIceCream.Write(Ingredients(ChoiceIngredient))
                    bnwIceCream.Write(Scoops)
                    bnwIceCream.Write(TotalPrice)
    
                    ' If the customer wants to save the 
    	 	' new order with a different name
                ElseIf Answer = "n" Or Answer = "N" Then
                    ' Ask the user to enter a name to remember the order
                    Console.Write("Please enter a name we will " & _
    			  "use to remember this order: ")
                    NameOfFile = Console.ReadLine()
                    NameOfFile = NameOfFile & ".icr"
    
                    stmIceCream = New FileStream(NameOfFile, FileMode.Create)
                    bnwIceCream = New BinaryWriter(stmIceCream)
    
                    Console.WriteLine(vbCrLf & "=-= Ice Cream Vending Machine =-=")
                    Console.WriteLine(" Saving Order: {0}", NameOfFile)
                    bnwIceCream.Write(Flavors(ChoiceFlavor))
                    bnwIceCream.Write(Containers(ChoiceContainer))
                    bnwIceCream.Write(Ingredients(ChoiceIngredient))
                    bnwIceCream.Write(Scoops)
                    bnwIceCream.Write(TotalPrice)
                Else
                    Console.WriteLine("Invalid Answer - We will close")
                    bnwIceCream.Close()
                    stmIceCream.Close()
                End If
            Else
    
                Dim stmIceCream As FileStream = _
    		New FileStream(NameOfFile, FileMode.Create)
                Dim bnwIceCream As BinaryWriter = New BinaryWriter(stmIceCream)
    
                Console.WriteLine(vbCrLf & "=-= Ice Cream Vending Machine =-=")
                Console.WriteLine(" Saving Order: {0}", NameOfFile)
                bnwIceCream.Write(Flavors(ChoiceFlavor))
                bnwIceCream.Write(Containers(ChoiceContainer))
                bnwIceCream.Write(Ingredients(ChoiceIngredient))
                bnwIceCream.Write(Scoops)
                bnwIceCream.Write(TotalPrice)
    
                bnwIceCream.Close()
                stmIceCream.Close()
            End If
        End Sub
    
        Public Sub Open()
            Dim NameOfFile As String
    
            Dim SelectedFlavor As String
            Dim SelectedContainer As String
            Dim SelectedIngredient As String
    
            ' Ask the user to enter a name of a previously saved order
            Console.Write("Please enter the name you previously " & _
    			  "gave to remember your order: ")
            NameOfFile = Console.ReadLine()
            NameOfFile = NameOfFile & ".icr"
    
            Dim stmIceCream As FileStream = New FileStream(NameOfFile, FileMode.Open)
            Dim bnrIceCream As BinaryReader = New BinaryReader(stmIceCream)
    
            ' Find out if this order was previously saved in the machine
            If File.Exists(NameOfFile) Then
                ' If so, open it
                SelectedFlavor = bnrIceCream.ReadString()
                SelectedContainer = bnrIceCream.ReadString()
                SelectedIngredient = bnrIceCream.ReadString()
                Scoops = bnrIceCream.ReadInt32()
                TotalPrice = bnrIceCream.ReadDouble()
    
                ' And display it to the user
                Console.WriteLine(vbCrLf & "=-= Ice Cream Vending Machine =-=")
                Console.WriteLine(" Previous Order: {0}", NameOfFile)
                Console.WriteLine("Flavor:      {0}", SelectedFlavor)
                Console.WriteLine("Container:   {0}", SelectedContainer)
                Console.WriteLine("Ingredient:  {0}", SelectedIngredient)
                Console.WriteLine("Scoops:      {0}", Scoops)
                Console.WriteLine("Total Price: {0:C}" & vbCrLf, TotalPrice)
    
                bnrIceCream.Close()
                stmIceCream.Close()
            Else
                Console.WriteLine("The name you entered is not " & _
    			  "registered in our previous orders")
            End If
        End Sub
    End Class
    Source File: Exercise.vb
    Imports System
    
    Public Class Exercise
        Public Shared Sub main()
            Dim IC As IceCream = New IceCream
            Dim Answer As String = "n"
    
            Console.Write("Have you ordered here before(y/n)? ")
            Answer = Console.ReadLine()
    
            If Answer = "y" Or Answer = "Y" Then
                IC.Open()
            Else
    
                IC.ProcessAnOrder()
    
                Console.Write("Do you want us to remember this order the next " & _
    			  "time you come to get your ice cream (y/n)? ")
                Answer = Console.ReadLine()
    
                If Answer = "y" Or Answer = "Y" Then
                    IC.Save()
                End If
            End If
    
        End Sub
    End Class
  2. Save the file and switch to the Command Prompt
  3. To compile it, type vbc /out:"Ice Cream Vending Machine".exe IceCream.vb Exercise.vb and press Enter
  4. To execute it, type "Ice Cream Vending Machine" and press Enter. Here is an example:
     
    Have you ordered here before(y/n)? y
    Please enter the name you previously gave to remember your order: Jane44
    
    =-= Ice Cream Vending Machine =-=
     Previous Order: Jane44.icr
    Flavor:      Chocolate Brownies
    Container:   Cone
    Ingredient:  Cookies
    Scoops:      2
    Total Price: $3.10
  5. Return to the IceCream.vb file
 
 
   
 

Previous Copyright © 2009-2010 FunctionX, Inc. Next