File Processing: Streaming Prerequisites



To support file processing, the .NET Framework provides the System.IO namespace that contains many different classes to handle almost any type of file operation you may need to perform. Therefore, to perform file processing, you can include the System.IO namespace in your project.

The parent class of file processing is Stream. With Stream, you can store data to a stream or you can retrieve data from a stream. Stream is an abstract class, which means that you cannot use it to declare a variable in your application. As an abstract class, Stream is used as the parent of the classes that actually implement the necessary operations. You will usually use a combination of classes to perform a typical operation. For example, some classes are used to create a stream object while some others are used to write data to the created stream.

Practical LearningPractical Learning: Introducing Streaming

  1. Start Microsoft Visual C# or Visual Studio and create a Windows Application named ClarksvilleIceCream2
  2. In the Properties window, change the form's Text to Ice Cream Vending Machine
  3. Design the form as follows:
    Ice Cream Vending Machine
    Control Name Text Additional Properties
    Label   Order Date:  
    DateTimePicker dtpOrderDate   Format: Short
    Label   Order Time:  
    DateTimePicker dtpOrderTime   Format: Time
    ShowUpDown: True
    Label   Flavor:  
    ComboBox cboFlavors   DropDownStyle: DropDownList
    Label   Container:  
    ComboBox cboContainers   DropDownStyle: DropDownList
    Label   Ingredient:  
    ComboBox cboIngredients   DropDownStyle: DropDownList
    Label   Scoops:  
    TextBox txtScoops 1 TextAlign: Right
    Label   Order Total:  
    TextBox txtOrderTotal 0.00 TextAlign: Right
    Button btnClose Close Click to end
  4. Click the combo box to the right of the Flavor label. Then, in the Properties, click the ellipsis button Ellipsis of Items property and create the list with:
    Cream of Cocoa
    Chocolate Chip
    Cherry Coke
    Butter Pecan
    Chocolate Cookie
    Chunky Butter
    Organic Strawberry
    Chocolate Brownies
    Caramel Au Lait
  5. Click OK
  6. Click the combo box to the right of the Container label. Then, in the Properties, click the ellipsis button Ellipsis of Items property and create the list with:
  7. Click OK
  8. Click the combo box to the right of the Ingredient label. Then, in the Properties, click the ellipsis button Ellipsis of Items property and create the list with:
    Mixed Nuts
    M & M
  9. Click OK
  10. On the form, click the Scoops text box and click the Events button Events of the Properties window 
  11. In the Events section of the Properties window, look for and double-click Leave to generate its event
  12. Implement it as follows:
    private void txtScoops_Leave(object sender, EventArgs e)
        double PriceContainer  = 0.00,
               PriceIngredient = 0.00,
               PriceScoops     = 0.00,
    	   OrderTotal      = 0.00;
        int NumberOfScoops     = 1;
        // The price of a container depends on which one the customer selected
        if( cboContainers.Text == "Cone" )
    	PriceContainer = 0.55;
        else if( cboContainers.Text == "Cup" )
    	PriceContainer = 0.75;
    	PriceContainer = 1.15;
        // Find out if the customer wants any ingredient at all
        if( this.cboIngredients.Text == "None" )
    	PriceIngredient = 0.00;
    	PriceIngredient = 0.95;
        try {
    	// Get the number of scoops
    	NumberOfScoops = int.Parse(this.txtScoops.Text);
    	if( NumberOfScoops == 1 )
    	        PriceScoops = 1.85;
    	else if( NumberOfScoops == 2 )
    	        PriceScoops = 2.55;
    	else // if( NumberOfScoops == 3 )
    	        PriceScoops = 3.25;
    	// Make sure the user selected a flavor, 
          	// otherwise, there is no reason to process an order
           	if( this.cboFlavors.Text != "" )
    	    OrderTotal = PriceScoops + PriceContainer + PriceIngredient;
    	    this.txtOrderTotal.Text = OrderTotal.ToString("F");
    	MessageBox.Show("The value you entered for the scoops is not valid" +
    	            "\nOnly natural numbers such as 1, 2, or 3 are allowed" +
    	                "\nPlease try again");
  13. Execute the application. Here is an example:
    Clarksville Ice Cream
  14. Close the form and return to Visual Studio

The Name of a File

Before performing file processing, one of your early decisions will consist of specifying the type of operation you want the user to perform. For example, the user may want to create a brand new file, open an existing file, or perform a routine operation on a file. In all or most cases, whether you are creating a new file or manipulating an existing one, you must specify the name of the file. You can do this by declaring a string variable but, as we will learn later on, most classes used to create a stream can take a string that represents the file.

If you are creating a new file, there are certainly some rules you must observe. The name of a file follows the directives of the operating system. On MS DOS and Windows 3.X (that is, prior to Microsoft Windows 9X), the file had to use the 8.3 format. The actual name had to have a maximum of 8 characters with restrictions on the characters that could be used. The user also had to specify three characters after a period. The three characters, known as the file extension, were used by the operating system to classify the file. That was all necessary for those 8-bit and 16-bit operating systems. Various rules have changed. For example, the names of folders and files on Microsoft Windows >= 95 can have up to 255 characters. The extension of the file is mostly left to the judgment of the programmer but the files are still using extensions. Applications can also be configured to save different types of files; that is, files with different extensions.

Author Note At the time of this writing, the rules for file names for Microsoft Windows were on the MSDN web site at Windows Development\Windows Base Services\Files and I/O\SDK Documentation\Storage\Storage Overview\File Management\Creating, Deleting, and Maintaining Files\Naming a File (because it is a web site and not a book, its pages can change anytime).

Based on this, if you declare a string variable to hold the name of the file, you can simply initialize the variable with the necessary name and its extension. Here is an example:

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

Practical LearningPractical Learning: Specifying the Name of a File

  1. To take advantage of Visual Basic, on the main menu, click Project -> Add Reference...
  2. In the .NET property page, click Microsoft.VisualBasic
  3. Click OK
  4. Return to the form and double-click the Close button
  5. Implement its 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",
        if (answer == System.Windows.Forms.DialogResult.Yes)
            string Filename =
                        "Please type your initials and press Enter",
                        "Ice Cream Vending Machine", "AA", 100, 100);
            if (Filename != "")
                // Wonderful
                MessageBox.Show("The ice cream order will not be saved");
        MessageBox.Show("Good Bye: It was a delight serving you");
  6. Scroll up in the file and, under the other using lines, type using System.IO;

The Path to a File

If you declare a string as above, the file will be created in the folder as the application. Otherwise, you can create your new file anywhere in the hard drive. To do that, you must provide a complete path where the file will reside. A path is a string that specifies the drive (such as A:, C:, or D:). The sections of a complete path string are separated by a backslash. For example, a path can the made of a folder followed by the name of the file. An example would be


A path can also consist of a drive followed by the name of the folder in which the file will be created. Here is an example:

C:\Program Files\Palermo.tde

A path can also indicate that the file will be created in a folder that itself is inside of another folder. In this case, remember that the names of folder must be separated by backslashes.

In Lesson 1, we saw that the backslash character is used to create or manage escape sequences and it can be included in a string value to make up an escape sequence. Because of this, every time you include a backslash in a string, the compiler thinks that you are trying to provide an escape sequence. In this case, if the combination of the backslash and the character that follows the backslash is not recognized as an escape sequence, you would get an error. To solve this problem, you have two alternatives. To indicate that the backslash must be considered as a character in its own right, you can double it. Here are examples:

using System;

class Exercise
    static int Main()
	string Filename = "C:\\Documents and Settings\\Employees.spr";

	return 0;

Alternative, you can keep one backslash in each placeholder but precede the value of the string with the @ symbol. Here is an example:

using System;

class Exercise
    static int Main()
	string Filename = @"C:\Documents and Settings\Employees.spr";

	return 0;

In the same way, you can declare a string variable to represent the name of an existing file that you plan to use in your program. You can also represent its path.

When providing a path to the file, if the drive you specify doesn't exist or cannot be read, the compiler would consider that the file doesn't exist. If you provide folders that don't exist in the drive, the compiler would consider that the file doesn't exist. This also means that the compiler will not create the folder(s) (the .NET Framework provides all means to create a folder but you must ask the compiler to create it; simply specifying a folder that doesn't exist will not automatically create it, even if you are creating a new file). Therefore, it is your responsibility to make sure that either the file or the path to the file is valid. As we will see in the next section, the compiler can check the existence of a file or path.


Previous Copyright © 2007 FunctionX, Inc. Next