Page d'Accueil

Fondamentaux du séquençage de fichier

 

Introduction

le séquençage d'un fichier consiste à effectuer une des opérations courantes sur le fichier, tel que le créer ou l'ouvrir. Cette opération de base peut être effectuée en utilisant une classe appelée FileStream. Vous pouvez utiliser un objet FileStream pour obtenir un stream prêt pour le traitement. En tant qu'une des classes les plus complètes du traitement de fichier du .NET Framework, FileStream est équipé de toutes les propriétés et méthodes nécessaires. Pour l'utiliser, vous devez d'abord déclarer sa variable. La classe est équipée de neuf constructeurs.

Un des constructeurs (le second) de la classe FileStream a la syntaxe suivante :

public FileStream(string path, FileMode mode);

Ce constructeur prend comme premier argument le nom du fichier ou son chemin. Le deuxième argument indique le type d'opération à exécuter sur le fichier. Voici un exemple :

using System;
using System.IO;

class Exercise
{
    static int Main()
    {
	string NameOfFile = "Persons.spr";

	FileStream fstPersons = new FileStream(NameOfFile, FileMode.Create);
	return 0;
    }
}

Étude pratiqueÉtude pratique : Créer un stream

  1. Pour créer un nouveau stream, changez la méthode SaveOrder() dans le fichier IceScream.cs comme suit :
     
    using System;
    using System.IO;
    
    namespace IceCream3
    {
        . . . No Change
    
            public void SaveOrder()
            {
                string NameOfFile;
    
                Console.Write("Please enter your initials or the " +
                              "name we will use to remember your order: ");
                NameOfFile = Console.ReadLine();
                
                if( File.Exists(NameOfFile) )
                {
                    char Answer;
    
                    Console.WriteLine("The file you entered exists already.");
                    Console.Write("Do you want to replace it(y/n)?" );
                    Answer = char.Parse(Console.ReadLine());
                    
                    FileStream stmIceScream =
    			new FileStream(NameOfFile, FileMode.Create);
    		
                    if( Answer == 'y' || Answer == 'Y' )
                        Console.WriteLine("The former order with the " +
                                          "same name will be replaced");
                    else if( Answer == 'n' || Answer == 'N' )
                    {
                        Console.WriteLine("Please enter a name we will " +
                                          "use to remember this order: ");
                        NameOfFile = Console.ReadLine();
                    }
                    else
                        Console.WriteLine("Invalid Answer - We will close");
    	
    				return;
    	    }
    	    else
    		Console.WriteLine("Great");
            }
    
            public void OpenOrder()
            {
                . . . No Change
            }
        }
    }
  2. sauvegardez le fichier

Stream d'écriture 

Une opération de séquençage est typiquement utilisée pour créer un stream. Une fois que le stream est prêt, vous pouvez en écrire des données. L'opération d'écriture est exécutée par diverses classes. Une de ces classes est BinaryWriter.

La classe BinaryWriter peut être utilisée pour écrire des valeurs des types de données primitifs (char, int, float, double, etc.). Pour utiliser une valeur BinaryWriter, vous pouvez d'abord déclarer sa variable. Pour ce faire, vous utiliserez un des trois constructeurs des classes. Un de ses constructeurs (le second) a la syntaxe suivante :

public BinaryWriter(Stream output);

Ce constructeur prend comme argument une valeur Stream, qui pourrait être une variable de FileStream. Voici un exemple :

using System;
using System.IO;

class Exercise
{
    static int Main()
    {
	string NameOfFile = "Persons.spr";

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

	return 0;
    }
}

La plupart des classes qui sont utilisées pour ajouter des valeurs Stream sont équipées d'une méthode appelée Write. C'est aussi le cas pour la classe BinaryWriter. Cette méthode prend comme argument la valeur qui doit être écrite au Stream. La méthode est prise en charge de sorte qu'il y ait une version pour chaque type de données primitif. Voici un exemple qui ajoute des chaînes de caractères à un fichier de création récente :

using System;
using System.IO;

class Exercise
{
    static int Main()
    {
	string NameOfFile = "Persons.spr";

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

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

	return 0;
    }
}

Fermeture d'un stream

Quand vous utilisez un stream, il demande des ressources du logiciel d'exploitation et les utilise tandis que le stream est disponible. Quand vous n'utiliserez plus le stream, vous devriez libérer les ressources et les rendre encore disponibles au logiciel d'exploitation de sorte que d'autres services puissent les utiliser. Ceci est fait par la fermeture du stream.

Pour fermer un stream, vous pouvez faire appel à la méthode Close() de la classe ou des classes que vous utilisée(s). Voici les exemples :

using System;
using System.IO;

class Exercise
{
    static int Main()
    {
	string NameOfFile = "Persons.spr";

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

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

	return 0;
    }
}

Étude pratiqueÉtude pratique : Inscription dans un stream

  1. Pour pouvoir compléter un fichier, changez la méthode SaveOrder () dans le fichier IceScream.cs comme suit :
     
    using System;
    using System.IO;
    
    namespace IceCream3
    {
            . . . No Change
    
            public void SaveOrder()
            {
                string strNameOfFile;
                
                Console.Write("Please enter your initials or the name " +
                                  "we will use to remember your order: ");
                strNameOfFile = Console.ReadLine();
                strNameOfFile = strNameOfFile + ".icr";
                
                // Find out if the user entered a name of a file 
                // that is already in the machine
                if (File.Exists(strNameOfFile))
                {
                    char answer;
                    
                    FileStream stmIceScream =
                        new FileStream(strNameOfFile, FileMode.Create);
                    BinaryWriter bnwIceScream =
                        new BinaryWriter(stmIceScream);
    
                    // 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 = char.Parse(Console.ReadLine());
    
                    // If the customer wants to replace it...
                    if (answer == 'y' || answer == 'Y')
                    {
                        // ... do so
                        Console.WriteLine("The former order with the same " +
                                          "name will be replaced");
    
                        Console.WriteLine(
    			"\n=-= Ice Scream Vending Machine =-=");
                        Console.WriteLine(" Saving Order: {0}", strNameOfFile);
                        bnwIceScream.Write(Flavor[ChoiceFlavor - 1]);
                        bnwIceScream.Write(Container[ChoiceContainer - 1]);
                        bnwIceScream.Write(Ingredient[ChoiceIngredient - 1]);
                        bnwIceScream.Write(Scoops);
                        bnwIceScream.Write(TotalPrice);
                    }
                    // If the customer wants to save the new order with 
                    // a different name
                    else if (answer == 'n' || answer == 'N')
                    {
                        // Ask the user to enter a name to remember the order
                        Console.Write("Please enter a name we will use " +
                                      "to remember this order: ");
                        strNameOfFile = Console.ReadLine();
                        strNameOfFile = strNameOfFile + ".icr";
    
                        stmIceScream =
    			new FileStream(strNameOfFile, FileMode.Create);
                        bnwIceScream = new BinaryWriter(stmIceScream);
    
                        Console.WriteLine(
    			"\n=-= Ice Scream Vending Machine =-=");
                        Console.WriteLine(" Saving Order: {0}", strNameOfFile);
                        bnwIceScream.Write(Flavor[ChoiceFlavor - 1]);
                        bnwIceScream.Write(Container[ChoiceContainer - 1]);
                        bnwIceScream.Write(Ingredient[ChoiceIngredient - 1]);
                        bnwIceScream.Write(Scoops);
                        bnwIceScream.Write(TotalPrice);
                    }
                    else
                        Console.WriteLine("Invalid Answer - We will close");
                    bnwIceScream.Close();
                    stmIceScream.Close();
                }
                else
                {
                    FileStream stmIceScream =
                        new FileStream(strNameOfFile, FileMode.Create);
                    BinaryWriter bnwIceScream =
                        new BinaryWriter(stmIceScream);
    
                    Console.WriteLine("\n=-= Ice Scream Vending Machine =-=");
                    Console.WriteLine(" Saving Order: {0}", strNameOfFile);
                    bnwIceScream.Write(Flavor[ChoiceFlavor - 1]);
                    bnwIceScream.Write(Container[ChoiceContainer - 1]);
                    bnwIceScream.Write(Ingredient[ChoiceIngredient - 1]);
                    bnwIceScream.Write(Scoops);
                    bnwIceScream.Write(TotalPrice);
    
                    bnwIceScream.Close();
                    stmIceScream.Close();
                }
            }
    
            public void OpenOrder()
            {
                . . . No Change
            }
        }
    }
  2. Exécutez l'application et l'examiner. Voici un exemple :
     
    =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
    Ice Scream Vending Machine
    -----------------------------------
    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? 8
    -----------------------------------
    What type of container do you want?
    1 - Cone
    2 - Cup
    3 - Bowl
    Your Choice? 2
    -----------------------------------
    Do you want an ingredient or not
    1 - No Ingredient
    2 - Peanuts
    3 - M & M
    4 - Cookies
    Your Choice? 3
    -----------------------------------
    How many scoops(1, 2, or 3)? 2
    -----------------------------------
    
    =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
    Ice Scream Order
    -----------------------------------
    Flavor:      Caramel Au Lait
    Container:   Cup
    Ingredient:  M & M
    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: LS
    
    =-= Ice Scream Vending Machine =-=
     Saving Order: LS.icr
    Press any key to continue . . .
  3. Fermer la fenêtre de DOS

Lecture dans un stream

Par opposition à l'inscription dans un stream, vous pouvez vouloir en lire des données existantes. Avant de faire ceci, vous pouvez d'abord indiquer votre intention à la classe stream en  utilisant l'agent recenseur FileMode. Ceci peut être fait en utilisant la classe FileStream comme suit :

using System;
using System.IO;

class Exercise
{
    static int Main()
    {
	string NameOfFile = "Persons.spr";
/*
	FileStream fstPersons = new FileStream(NameOfFile, FileMode.Create);
	BinaryWriter wrtPersons = new BinaryWriter(fstPersons);

	wrtPersons.Write("James Bloch");
	wrtPersons.Write("Catherina Wallace");
	wrtPersons.Write("Bruce Lamont");
	wrtPersons.Write("Douglas Truth");
		
	wrtPersons.Close();
	fstPersons.Close();
*/
	FileStream fstPersons = new FileStream(NameOfFile, FileMode.Open);

	return 0;
    }
}

Une fois que le stream est prêt, vous pouvez vous préparer à lire ses données. Pour soutenir ceci, vous pouvez utiliser la classe BinaryReader. Cette classe fournit deux constructeurs. Un des constructeurs (le premier) a la syntaxe suivante :

public BinaryReader(Stream input);

Ce constructeur prend comme argument une valeur Stream, qui pourrait être un objet de FileStream. Après la déclaration d'une variable FileStream en utilisant ce constructeur, vous pouvez lire ses données. Pour ce faire, vous pouvez appeler une méthode appropriée. Cette classe fournit une méthode appropriée pour chaque type de données primitif.

Après avoir utiliser le stream, vous devriez le fermer pour reprendre les ressources qu'il utilisait. Ceci est fait en appelant la méthode Close()  .

Voici un exemple d'utilisation des méthodes mentionnées :

using System;
using System.IO;

class Exercise
{
    static int Main()
    {
	string NameOfFile = "Persons.spr";
/*
	FileStream fstPersons = new FileStream(NameOfFile, FileMode.Create);
	BinaryWriter wrtPersons = new BinaryWriter(fstPersons);

	wrtPersons.Write("James Bloch");
	wrtPersons.Write("Catherina Wallace");
	wrtPersons.Write("Bruce Lamont");
	wrtPersons.Write("Douglas Truth");
		
	wrtPersons.Close();
	fstPersons.Close();
*/
	FileStream fstPersons = new FileStream(NameOfFile, FileMode.Open);
	BinaryReader rdrPersons = new BinaryReader(fstPersons);
	string strLine = null;

	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();

	return 0;
    }
}

Étude pratiqueÉtude pratique : Lecture d'un steram

  1. Pour pouvoir rechercher les données à partir d'un fichier existant, changez le fichier IceCream.cs comme suit :
     
    using System;
    using System.IO;
    
    namespace IceCream3
    {
        delegate void Request();
    
        // This class is used to create and manage an ice scream
        // and to process an order
        public sealed class IceScream
        {
            // This is the base price of an ice scream
            // Optional values may be added to it
            public const decimal BasePrice = 1.55M;
    
            // These arrays are used to build the components 
            // of various ice screams
            // In C#, we can allocate an array's memory in 
            // the body of the class
            private string[] Flavor;
            private string[] Container;
            private string[] Ingredient;
    
            // Additional factor used to process an ice scream order
            private int Scoops;
            private decimal TotalPrice;
    
            // Variables that will hold the user's choice
            // These are declared "globally" so they can be 
            // shared among methods
            int ChoiceFlavor;
            int ChoiceContainer;
            int ChoiceIngredient;
    
            // This default constructor is the best place for 
            // us to initialize the array
            public IceScream()
            {
                Flavor = new string[10];
                Flavor[0] = "Vanilla";
                Flavor[1] = "Cream of Cocoa";
                Flavor[2] = "Chocolate Chip";
                Flavor[3] = "Organic Strawberry";
                Flavor[4] = "Butter Pecan";
                Flavor[5] = "Cherry Coke";
                Flavor[6] = "Chocolate Brownies";
                Flavor[7] = "Caramel Au Lait";
                Flavor[8] = "Chunky Butter";
                Flavor[9] = "Chocolate Cookie";
    
                Ingredient = new string[4];
                Ingredient[0] = "No Ingredient";
                Ingredient[1] = "Peanuts";
                Ingredient[2] = "M & M";
                Ingredient[3] = "Cookies";
    
                Container = new string[3];
                Container[0] = "Cone";
                Container[1] = "Cup";
                Container[2] = "Bowl";
            }
    
            // This method requests a flavor from the user and
            // returns the choice
            public void 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 (int i = 0; i < Flavor.Length; i++)
                            Console.WriteLine("{0} - {1}", i + 1, Flavor[i]);
                        Console.Write("Your Choice? ");
                        ChoiceFlavor = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)	// display an appropriate message
                    {
                        Console.WriteLine("You must enter a valid number " +
                                          "and no other character!");
                    }
    
                    // If the user typed an invalid number out of the 
                    // allowed range
                    // let him or her know and provide another chance
                    if (ChoiceFlavor < 1 || ChoiceFlavor > Flavor.Length)
                        Console.WriteLine("Invalid Choice - Try Again!\n");
                } while (ChoiceFlavor < 1 || ChoiceFlavor > Flavor.Length);
            }
    
            // This method allows the user to select a container
            public void 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 (int i = 0; i < Container.Length; i++)
                            Console.WriteLine("{0} - {1}", i + 1, Container[i]);
                        Console.Write("Your Choice? ");
                        ChoiceContainer = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)	// display an appropriate message
                    {
                        Console.WriteLine("You must enter a valid " +
                                          "number and no other character!");
                    }
    
                    // If the user typed an invalid number out of the 
                    // allowed range
                    // let him or her know and provide another chance
                    if ((ChoiceContainer < 1) ||
                        (ChoiceContainer > Container.Length))
                        Console.WriteLine("Invalid Choice - Try Again!");
                } while ((ChoiceContainer < 1) ||
                         (ChoiceContainer > Container.Length));
            }
    
            public void ChooseIngredient()
            {
                do
                {
                    try
                    {
                        Console.WriteLine("Do you want an ingredient or not");
                        for (int i = 0; i < Ingredient.Length; i++)
                            Console.WriteLine("{0} - {1}",
                                              i + 1,
                                              Ingredient[i]);
                        Console.Write("Your Choice? ");
                        ChoiceIngredient = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("You must enter a valid " +
                                          "number and no other character!");
                    }
    
                    if ((ChoiceIngredient < 1) ||
                        (ChoiceIngredient > Ingredient.Length))
                        Console.WriteLine("Invalid Choice - Try Again!");
                } while ((ChoiceIngredient < 1) ||
                         (ChoiceIngredient > Ingredient.Length));
            }
    
            public void SpecifyNumberOfScoops()
            {
                do
                {
                    try
                    {
                        Console.Write("How many scoops(1, 2, or 3)? ");
                        Scoops = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("You must enter a valid number " +
                                          "and no other character!");
                    }
    
                    if (Scoops < 1 || Scoops > 3)
                        Console.WriteLine("Invalid Choice - Try Again!");
                } while (Scoops < 1 || Scoops > 3);
            }
    
            // This method is used to process a customer order
            // It uses the values of the above methods
            public void ProcessAnOrder()
            {
                //			int ChoiceFlavor;
                //			int ChoiceContainer;
                //			int ChoiceIngredient;
                decimal PriceIngredient, PriceScoop;
    
                // Let the user know that this is a vending machine
                Console.WriteLine("=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=");
                Console.WriteLine("Ice Scream Vending Machine");
                Console.WriteLine("-----------------------------------");
    
                // Let the user select the components of the ice scream
                Request Get = new Request(ChooseFlavor);
                Get();
                Console.WriteLine("-----------------------------------");
                Get = new Request(ChooseContainer);
                Get();
                Console.WriteLine("-----------------------------------");
                Get = new Request(ChooseIngredient);
                Get();
                Console.WriteLine("-----------------------------------");
                Get = new Request(SpecifyNumberOfScoops);
                Get();
                Console.WriteLine("-----------------------------------");
    
                // If the user selects an ingredient instead of "No Ingredient",
                // add $0.50 to the order
                if ((ChoiceIngredient == 2) ||
                    (ChoiceIngredient == 3) ||
                    (ChoiceIngredient == 4))
                    PriceIngredient = 0.50M;
                else
                    PriceIngredient = 0.00M;
    
                // Instead of multiplying a number scoops to a value,
                // We will use an incremental value depending on 
                // the number of scoops
                if (Scoops == 1)
                    PriceScoop = 0.65M;
                else if (Scoops == 2)
                    PriceScoop = 1.05M;
                else
                    PriceScoop = 1.55M;
    
                // Calculate the total price of the ice scream
                TotalPrice = BasePrice + PriceScoop + PriceIngredient;
    
                // Create the ice scream...
    
                // And display a receipt to the user
                DisplayReceipt();
            }
    
            // This method is used to display a receipt to the user
            public void DisplayReceipt()
            {
                Console.WriteLine("\n=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=");
                Console.WriteLine("Ice Scream Order");
                Console.WriteLine("-----------------------------------");
                Console.WriteLine("Flavor:      {0}",
                                  Flavor[ChoiceFlavor - 1]);
                Console.WriteLine("Container:   {0}",
                                  Container[ChoiceContainer - 1]);
                Console.WriteLine("Ingredient:  {0}",
                                  Ingredient[ChoiceIngredient - 1]);
                Console.WriteLine("Scoops:      {0}", Scoops);
                Console.WriteLine("Total Price: {0:C}", TotalPrice);
                Console.WriteLine("=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=\n");
            }
    
            public void SaveOrder()
            {
                string strNameOfFile;
                
                Console.Write("Please enter your initials or the name " +
                                  "we will use to remember your order: ");
                strNameOfFile = Console.ReadLine();
                strNameOfFile = strNameOfFile + ".icr";
                
                // Find out if the user entered a name of a file 
                // that is already in the machine
                if (File.Exists(strNameOfFile))
                {
                    char answer;
                    
                    FileStream stmIceScream =
                        new FileStream(strNameOfFile, FileMode.Create);
                    BinaryWriter bnwIceScream =
                        new BinaryWriter(stmIceScream);
    
                    // 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 = char.Parse(Console.ReadLine());
    
                    // If the customer wants to replace it...
                    if (answer == 'y' || answer == 'Y')
                    {
                        // ... do so
                        Console.WriteLine("The former order with the same " +
                                          "name will be replaced");
    
                        Console.WriteLine(
    			"\n=-= Ice Scream Vending Machine =-=");
                        Console.WriteLine(" Saving Order: {0}", strNameOfFile);
                        bnwIceScream.Write(Flavor[ChoiceFlavor - 1]);
                        bnwIceScream.Write(Container[ChoiceContainer - 1]);
                        bnwIceScream.Write(Ingredient[ChoiceIngredient - 1]);
                        bnwIceScream.Write(Scoops);
                        bnwIceScream.Write(TotalPrice);
                    }
                    // If the customer wants to save the new order with 
                    // a different name
                    else if (answer == 'n' || answer == 'N')
                    {
                        // Ask the user to enter a name to remember the order
                        Console.Write("Please enter a name we will use " +
                                      "to remember this order: ");
                        strNameOfFile = Console.ReadLine();
                        strNameOfFile = strNameOfFile + ".icr";
    
                        stmIceScream = 
    			new FileStream(strNameOfFile, FileMode.Create);
                        bnwIceScream = new BinaryWriter(stmIceScream);
    
                        Console.WriteLine(
    			"\n=-= Ice Scream Vending Machine =-=");
                        Console.WriteLine(" Saving Order: {0}", strNameOfFile);
                        bnwIceScream.Write(Flavor[ChoiceFlavor - 1]);
                        bnwIceScream.Write(Container[ChoiceContainer - 1]);
                        bnwIceScream.Write(Ingredient[ChoiceIngredient - 1]);
                        bnwIceScream.Write(Scoops);
                        bnwIceScream.Write(TotalPrice);
                    }
                    else
                        Console.WriteLine("Invalid Answer - We will close");
                    bnwIceScream.Close();
                    stmIceScream.Close();
                }
                else
                {
                    FileStream stmIceScream =
                        new FileStream(strNameOfFile, FileMode.Create);
                    BinaryWriter bnwIceScream =
                        new BinaryWriter(stmIceScream);
    
                    Console.WriteLine("\n=-= Ice Scream Vending Machine =-=");
                    Console.WriteLine(" Saving Order: {0}", strNameOfFile);
                    bnwIceScream.Write(Flavor[ChoiceFlavor - 1]);
                    bnwIceScream.Write(Container[ChoiceContainer - 1]);
                    bnwIceScream.Write(Ingredient[ChoiceIngredient - 1]);
                    bnwIceScream.Write(Scoops);
                    bnwIceScream.Write(TotalPrice);
    
                    bnwIceScream.Close();
                    stmIceScream.Close();
                }
            }
    
            public void OpenOrder()
            {
                string strNameOfFile;
    		
                string SelectedFlavor;
                string SelectedContainer;
                string SelectedIngredient;
    
    	    // 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: ");
    	    strNameOfFile = Console.ReadLine();
                strNameOfFile = strNameOfFile + ".icr";
    
    	    FileStream stmIceScream =
                    new FileStream(strNameOfFile, FileMode.Open);
    	    BinaryReader bnrIceScream =
                    new BinaryReader(stmIceScream);
                
                // Find out if this order was previously saved in the machine
                if (File.Exists(strNameOfFile))
                {
                    // If so, open it
                    SelectedFlavor = bnrIceScream.ReadString();
                    SelectedContainer = bnrIceScream.ReadString();
                    SelectedIngredient = bnrIceScream.ReadString();
                    Scoops = bnrIceScream.ReadInt32();
                    TotalPrice = bnrIceScream.ReadDecimal();
                    
                    // And display it to the user
                    Console.WriteLine("\n=-= Ice Scream Vending Machine =-=");
                    Console.WriteLine(" Previous Order: {0}", strNameOfFile);
                    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}\n", TotalPrice);
                    
                    bnrIceScream.Close();
                    stmIceScream.Close();
                }
                else
                    Console.WriteLine("The name you entered is not " +
                                      "registered in our previous orders");
            }
        }
    }
  2. Accédez au fichier Program.cs et changez le comme suit :
     
    using System;
    
    namespace IceCream3
    {
        class Program
        {
            static int Main(string[] args)
            {
                char answer = 'n';
                IceScream ic = new IceScream();
                Request process = new Request(ic.ProcessAnOrder);
               
                Console.Write("Do you want to re-order a previously " +
                              "saved order(y/n)? ");
                answer = char.Parse(Console.ReadLine());
                
                if (answer == 'y' || answer == 'Y')
                    ic.OpenOrder();
                else
                {
                    process();
                    Console.Write("Do you want us to remember this " +
                                  "order the next time you come to " +
                                  "get your ice scream (y/n)? ");
                    answer = char.Parse(Console.ReadLine());
                    if (answer == 'y' || answer == 'Y')
                        ic.SaveOrder();
                    else
                        Console.WriteLine("\nIt was nice serving you." +
                                          "\nCome Again!!!\n");
                }
                return 0;
            }
        }
    }
  3. Exécutez l'application et l'examiner. Voici un exemple :
     
    Do you want to re-order a previously saved order(y/n)? Y
    Please enter the name you previously gave to remember your order: LS
    
    =-= Ice Scream Vending Machine =-=
     Previous Order: LS.icr
    Flavor:      Caramel Au Lait
    Container:   Cup
    Ingredient:  M & M
    Scoops:      2
    Total Price: $3.10
    
    Press any key to continue . . .
  4. Fermez la fenêtre DOS
  5. Exécutez encore l'application et l'examiner. Voici un exemple :
     
    Do you want to re-order a previously saved order(y/n)? w
    =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
    Ice Scream Vending Machine
    -----------------------------------
    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? 5
    -----------------------------------
    What type of container do you want?
    1 - Cone
    2 - Cup
    3 - Bowl
    Your Choice? 2
    -----------------------------------
    Do you want an ingredient or not
    1 - No Ingredient
    2 - Peanuts
    3 - M & M
    4 - Cookies
    Your Choice? 1
    -----------------------------------
    How many scoops(1, 2, or 3)? 1
    -----------------------------------
    
    =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
    Ice Scream Order
    -----------------------------------
    Flavor:      Butter Pecan
    Container:   Cup
    Ingredient:  No Ingredient
    Scoops:      1
    Total Price: $2.20
    =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
    
    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: DIC
    
    =-= Ice Scream Vending Machine =-=
     Saving Order: DIC.icr
    Press any key to continue . . .
  6. Fermez la fenêtre DOS
  7. Exécutez encore l'application et l'examiner. Voici un exemple :
     
    Do you want to re-order a previously saved order(y/n)? n
    =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
    Ice Scream Vending Machine
    -----------------------------------
    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? 9
    -----------------------------------
    What type of container do you want?
    1 - Cone
    2 - Cup
    3 - Bowl
    Your Choice? 3
    -----------------------------------
    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)? 3
    -----------------------------------
    
    =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
    Ice Scream Order
    -----------------------------------
    Flavor:      Chunky Butter
    Container:   Bowl
    Ingredient:  Cookies
    Scoops:      3
    Total Price: $3.60
    =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
    
    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: LS
    The file you entered exists already.
    Do you want to replace it(y/n)?Y
    The former order with the same name will be replaced
    
    =-= Ice Scream Vending Machine =-=
     Saving Order: LS.icr
    Press any key to continue . . .
  8. Fermez la fenêtre DOS
  

Précédent Copyright © 2007, Yevol Suivant