Home

Fundamentals of File Streaming

 

Introduction

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 FileStream(string path, FileMode mode);

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:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace FileProcessing1
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string Filename = "Employees.spr";

            FileStream fstPersons = new FileStream(Filename,
                FileMode.Create);
        }
    }
}

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 variable. 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 BinaryWriter(Stream output);

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

namespace FileProcessing1
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string Filename = "Employees.spr";

            FileStream fstPersons = new FileStream(Filename,
                FileMode.Create);
            BinaryWriter wrtPersons = new BinaryWriter(fstPersons);
        }
    }
}

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

private void btnSave_Click(object sender, EventArgs e)
{
        string Filename = "Employees.spr";

        FileStream fstPersons = new FileStream(Filename,
                FileMode.Create);
        BinaryWriter wrtPersons = new BinaryWriter(fstPersons);
    
        wrtPersons.Write(txtPerson1.Text);
        wrtPersons.Write(txtPerson2.Text);
        wrtPersons.Write(txtPerson3.Text);
        wrtPersons.Write(txtPerson4.Text);

        txtPerson1.Text = "";
        txtPerson2.Text = "";
        txtPerson3.Text = "";
        txtPerson4.Text = "";
}

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 void btnSave_Click(object sender, EventArgs e)
{
        string Filename = "Employees.spr";

        FileStream fstPersons = new FileStream(Filename,
                FileMode.Create);
        BinaryWriter wrtPersons = new BinaryWriter(fstPersons);
    
        wrtPersons.Write(txtPerson1.Text);
        wrtPersons.Write(txtPerson2.Text);
        wrtPersons.Write(txtPerson3.Text);
        wrtPersons.Write(txtPerson4.Text);

        txtPerson1.Text = "";
        txtPerson2.Text = "";
        txtPerson3.Text = "";
        txtPerson4.Text = "";

      wrtPersons.Close();
      fstPersons.Close();
}

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 void btnClose_Click(object sender, EventArgs e)
    {
        System.Windows.Forms.DialogResult answer =
    	 MessageBox.Show("Do you want to save this order to remember it " +
                             "the next time you come to " +
                             "get your ice scream?",
                             "Ice Cream Vending Machine",
                 		 MessageBoxButtons.YesNo,
                 		 MessageBoxIcon.Question);
    
        if (answer == System.Windows.Forms.DialogResult.Yes)
        {
            string Filename =
                    Microsoft.VisualBasic.Interaction.InputBox(
                        "Please type your initials and press Enter",
                        "Ice Cream Vending Machine", "AA", 100, 100);
            if (Filename != "")
            {
                Filename = Filename + ".icr";
    
                FileStream stmIceCream =
    			new FileStream(Filename, FileMode.Create);
    	    BinaryWriter bnwIceCream =
    	                    new BinaryWriter(stmIceCream);
    
    	    bnwIceCream.Write(dtpOrderDate.Value.ToShortDateString());
    	    bnwIceCream.Write(dtpOrderTime.Value.ToShortTimeString());
    	    bnwIceCream.Write(cboFlavors.Text);
    	    bnwIceCream.Write(cboContainers.Text);
    	    bnwIceCream.Write(cboIngredients.Text);
    	    bnwIceCream.Write(txtScoops.Text);
    	    bnwIceCream.Write(txtOrderTotal.Text);
    
    	    bnwIceCream.Close();
    	    stmIceCream.Close();
    
    	    MessageBox.Show("The order has been saved");
            }
            else
                MessageBox.Show("The ice cream order will not be saved");
        }
    
        MessageBox.Show("Good Bye: It was a delight serving you");
        Close();
    }
  2. Execute the application and test it. Here is an example:
     
    Clarksville Ice Cream
    Clarksville Ice Cream
    Clarksville Ice Cream
    Clarksville Ice Cream
  3. Close the DOS window

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 void btnOpen_Click(object sender, EventArgs e)
{
    string Filename = "Employees.spr";
    FileStream fstPersons = new FileStream(Filename, FileMode.Open);
}

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 BinaryReader(Stream input);

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 void btnOpen_Click(object sender, EventArgs e)
{
            string Filename = "Employees.spr";
            FileStream fstPersons = new FileStream(Filename, FileMode.Open);
            BinaryReader rdrPersons = new BinaryReader(fstPersons);

            txtPerson1.Text = rdrPersons.ReadString();
            txtPerson2.Text = rdrPersons.ReadString();
            txtPerson3.Text = rdrPersons.ReadString();
            txtPerson4.Text = rdrPersons.ReadString();

            rdrPersons.Close();
            fstPersons.Close();
}

Practical LearningPractical Learning: Reading From a Stream

  1. Display the form
  2. Double-click outside of any control, such as just under the title bar to generate the Load event of the form
     
    Clarksville Ice Cream
  3. Implement the event as follows:
     
    private void Form1_Load(object sender, EventArgs e)
    {
        string Filename =
                    Microsoft.VisualBasic.Interaction.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 != "")
        {
            Filename = Filename + ".icr";
    
            string OrderDate;
            string OrderTime;
            string SelectedFlavor;
            string SelectedContainer;
            string SelectedIngredient;
            string Scoops;
            string OrderTotal;
    
            FileStream stmIceCream =
                            new FileStream(Filename, FileMode.Open);
            BinaryReader bnrIceCream =
                            new BinaryReader(stmIceCream);
    
            // Find out if this order was previously saved in the machine
            if (File.Exists(Filename))
            {
                // If so, open it
                OrderDate = bnrIceCream.ReadString();
                OrderTime = bnrIceCream.ReadString();
                SelectedFlavor = bnrIceCream.ReadString();
                SelectedContainer = bnrIceCream.ReadString();
                SelectedIngredient = bnrIceCream.ReadString();
                Scoops = bnrIceCream.ReadString();
                OrderTotal = bnrIceCream.ReadString();
    
                // 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;
    
                bnrIceCream.Close();
                stmIceCream.Close();
            }
            else
                MessageBox.Show("It looks like you have not previously " +
                                "ordered an ice cream here");
        }
    }
  4. Execute the application and test it. Here is an example:
     
    Microsoft Visual Basic Input Box
    Clarksville Ice Cream
  5. Close the form
 

Previous Copyright © 2007 FunctionX, Inc. Next