Home

Details on File Processing

 

Exception Handling in File Processing

 

Finally

So far, to handle exceptions, we were using the try, catch, and throw keywords. These allowed us to perform normal assignments in a try section and then handle an exception, if any, in a catch block.

In the previous lesson, we mentioned that, when you create a stream, the operating system must allocate resources and dedicate them to the file processing operations. Additional resources may be provided for the object that is in charge of writing to, or reading from, the stream. We also saw that, when the streaming was over, we should free the resources and give them back to the operating system. To do this, we called the Close() method of the variable that was using resources.

More than any other assignment, file processing is in prime need of exception handling. As we will see in the next section, during file processing, there are many things that can go wrong. For this reason, the creation and/or management of streams should be performed in a try block to get ready to handle exceptions that would occur. Besides actually handling exceptions, the C# language provides a special keyword used free resources. This keyword is finally.

The finally keyword is used to create a section of an exception. Like catch, a finally block cannot exist by itself. It can be created following a try section. The formula used would be:

try
{
}
finally
{
}

Based on this, the finally section has a body of its own, delimited by its curly brackets. Like catch, the finally section is created after the try section. Unlike catch, finally never has parentheses and never takes arguments. Unlike catch, the finally section is always executed. Because the finally clause always gets executed, you can include any type of code in it but it is usually appropriate to free the resources that were allocated earlier. Here is an example:

using System;
using System.IO;

class Exercise
{
    static int Main()
    {
	string NameOfFile = "Members.clb";
	
	FileStream fstPersons = new FileStream(NameOfFile, FileMode.Create);
	BinaryWriter wrtPersons = new BinaryWriter(fstPersons);

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

	return 0;
    }
}

In the same way, you can use a finally section to free resources used when reading from a stream:

 

 
using System;
using System.IO;

class Exercise
{
	static int Main()
	{
		/*		string NameOfFile = "Members.clb";

				FileStream fstMembers = new FileStream(NameOfFile, FileMode.Create);
				BinaryWriter wrtMembers = new BinaryWriter(fstMembers);

				try 
				{
					wrtMembers.Write("James Bloch");
					wrtMembers.Write("Catherina Wallace");
					wrtMembers.Write("Bruce Lamont");
					wrtMembers.Write("Douglas Truth");
				}
				finally
				{
					wrtMembers.Close();
					fstMembers.Close();
				}
		*/

		string NameOfFile = "Members.clb";
		string strLine = null;

		FileStream fstMembers = new FileStream(NameOfFile, FileMode.Open);
		BinaryReader rdrMembers = new BinaryReader(fstMembers);

		try 
		{
			strLine = rdrMembers.ReadString();
			Console.WriteLine(strLine);
			strLine = rdrMembers.ReadString();
			Console.WriteLine(strLine);
			strLine = rdrMembers.ReadString();
			Console.WriteLine(strLine);
			strLine = rdrMembers.ReadString();
			Console.WriteLine(strLine);
		}
		finally
		{
			rdrMembers.Close();
			fstMembers.Close();
		}

		return 0;
	}
}

Of course, since the whole block of code starts with a try section, it is used for exception handling. This means that you can add the necessary and appropriate catch section(s) but you don't have to.

Practical LearningPractical Learning: Finally Releasing Resources

  1. Start Notepad
  2. Open the IceCream.cs file from the IceCream4 folder and make the following changes (if you don't have the file, create a new file in Notepad and type the following in the empty file then save it as IceCream.cs in a new folder named IceCream4):
     
    using System;
    using System.IO;
    
    namespace VendingMachine
    {
    	// This class is used to create and manage an ice cream
    	// and to process an order
    	sealed class IceCream
    	{
    		// This is the base price of an ice cream
    		// Optional values may be added to it
    		public const decimal BasePrice = 1.55M;
    
    		// 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 string[] Flavor;
    		private string[] Container;
    		private string[] Ingredient;
    
    		// Additional factor used to process an ice cream 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 IceCream()
    		{
    			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("\n=-= Ice Cream Vending Machine =-=");
    			Console.WriteLine(" ------ New Customer Order ------");
    
    			// 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 || 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 cream
    			TotalPrice = BasePrice + PriceScoop + PriceIngredient;
    
    			// Create the ice cream...
    
    			// And display a receipt to the user
    			DisplayReceipt();
    		}
    
    		// This method is used to display a receipt to the user
    		public void DisplayReceipt()
    		{
    			Console.WriteLine("\nIce Cream Order");
    			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}\n", TotalPrice);
    		}
    		
    		public void SaveOrder()
    		{
    			string NameOfFile;
    
    			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) )
    			{
    				char Answer;
    
    				FileStream stmIceCream = new FileStream(NameOfFile, FileMode.Create);
    				BinaryWriter bnwIceCream = new BinaryWriter(stmIceCream);
    
    				try 
    				{
    					// 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 Cream Vending Machine =-=");
    						Console.WriteLine(" Saving Order: {0}", NameOfFile);
    						bnwIceCream.Write(Flavor[ChoiceFlavor-1]);
    						bnwIceCream.Write(Container[ChoiceContainer-1]);
    						bnwIceCream.Write(Ingredient[ChoiceIngredient-1]);
    						bnwIceCream.Write(Scoops);
    						bnwIceCream.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: ");
    						NameOfFile = Console.ReadLine();
    						NameOfFile = NameOfFile + ".icr";
    
    						stmIceCream = new FileStream(NameOfFile, FileMode.Create);
    						bnwIceCream = new BinaryWriter(stmIceCream);
    
    						Console.WriteLine("\n=-= Ice Cream Vending Machine =-=");
    						Console.WriteLine(" Saving Order: {0}", NameOfFile);
    						bnwIceCream.Write(Flavor[ChoiceFlavor-1]);
    						bnwIceCream.Write(Container[ChoiceContainer-1]);
    						bnwIceCream.Write(Ingredient[ChoiceIngredient-1]);
    						bnwIceCream.Write(Scoops);
    						bnwIceCream.Write(TotalPrice);
    					}
    					else
    						Console.WriteLine("Invalid Answer - We will close");
    				}
    				finally 
    				{
    					bnwIceCream.Close();
    					stmIceCream.Close();
    				}
    			}
    			else
    			{
    				FileStream stmIceCream = new FileStream(NameOfFile, FileMode.Create);
    				BinaryWriter bnwIceCream = new BinaryWriter(stmIceCream);
    
    				try 
    				{
    					Console.WriteLine("\n=-= Ice Cream Vending Machine =-=");
    					Console.WriteLine(" Saving Order: {0}", NameOfFile);
    					bnwIceCream.Write(Flavor[ChoiceFlavor-1]);
    					bnwIceCream.Write(Container[ChoiceContainer-1]);
    					bnwIceCream.Write(Ingredient[ChoiceIngredient-1]);
    					bnwIceCream.Write(Scoops);
    					bnwIceCream.Write(TotalPrice);
    				}
    				finally 
    				{
    					bnwIceCream.Close();
    					stmIceCream.Close();
    				}
    			}
    		}
    
    		public void OpenOrder()
    		{
    			string NameOfFile;
    		
    			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: ");
    			NameOfFile = Console.ReadLine();
    			NameOfFile = NameOfFile + ".icr";
    
    			FileStream stmIceCream = new FileStream(NameOfFile, FileMode.Open);
    			BinaryReader bnrIceCream = new BinaryReader(stmIceCream);
    
    			try 
    			{
    				// Find out if this order was previously saved in the machine
    				if( File.Exists(NameOfFile) )
    				{
    					// If so, open it
    					SelectedFlavor = bnrIceCream.ReadString();
    					SelectedContainer = bnrIceCream.ReadString();
    					SelectedIngredient = bnrIceCream.ReadString();
    					Scoops = bnrIceCream.ReadInt32();
    					TotalPrice = bnrIceCream.ReadDecimal();
    
    					// And display it to the user
    					Console.WriteLine("\n=-= 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}\n", TotalPrice);
    				}
    				else
    					Console.WriteLine("The name you entered is not registered in our previous orders");
    			}
    			finally 
    			{
    				bnrIceCream.Close();
    				stmIceCream.Close();
    			}
    		}
    	}
    }
     
    As a reminder, here is the content of the Exercise.cs file:
     
    using System;
    
    class Exercise
    {
    	static int Main()
    	{
    		VendingMachine.IceCream IS = new VendingMachine.IceCream();
    		char Answer = 'n';
    
    		Console.Write("Have you ordered here before(y/n)? ");
    		Answer = char.Parse(Console.ReadLine());
    
    		if( Answer == 'y' || Answer == 'Y' )
    			IS.OpenOrder();
    		else
    		{
    			IS.ProcessAnOrder();
    
    			Console.Write("Do you want us to remember this order the next time you come to get your ice cream (y/n)? ");
    			Answer = char.Parse(Console.ReadLine());
    
    			if( Answer == 'y' || Answer == 'Y' )
    				IS.SaveOrder();
    		}
    
    		return 0;
    	}
    }
  3. Open the Command Prompt and change to the directory that contains the above Exercise.cs file
  4. To compile it, type csc /out:"Ice Cream Vending Machine".exe IceCream.cs Exercise.cs and press Enter
  5. To execute it, type "Ice Cream Vending Machine" and press Enter
  6. Return to the IceCream.cs file

.NET Framework Exception Handling for File Processing

In the previous lesson as our introduction to file processing, we behaved as if everything was alright. Unfortunately, file processing can be very strict in its assignments. Based on this, the .NET Framework provides various Exception-oriented classes to deal with almost any type of exception you can think of.

One of the most important aspects of file processing is the name of the file that will be dealt with. In some cases you can provide this name to the application or document. In some other cases, you would let the user specify the name of the path. Regardless of how the name of the file would be provided to the operating system, when this name is acted upon, the compiler be asked to work on the file. If the file doesn't exist, the operation cannot be carried. Furthermore, the compiler would throw an error. There are many other exceptions that can thrown as a result of something going bad during file processing:

FileNotFoundException: The exception thrown when a file has been found is of type FileNotFoundException. Here is an example of handling it:

using System;
using System.IO;

class Exercise
{
	static int Main()
	{
/*
		string NameOfFile = "Members.clb";

		FileStream fstMembers = new FileStream(NameOfFile, FileMode.Create);
		BinaryWriter wrtMembers = new BinaryWriter(fstMembers);

		try 
		{
			wrtMembers.Write("James Bloch");
			wrtMembers.Write("Catherina Wallace");
			wrtMembers.Write("Bruce Lamont");
			wrtMembers.Write("Douglas Truth");
		}
		finally
		{
			wrtMembers.Close();
			fstMembers.Close();
		}
*/

		string NameOfFile = "Associates.clb";
		string strLine = null;

		try 
		{
			FileStream fstMembers = new FileStream(NameOfFile, FileMode.Open);
			BinaryReader rdrMembers = new BinaryReader(fstMembers);

			try 
			{
				strLine = rdrMembers.ReadString();
				Console.WriteLine(strLine);
				strLine = rdrMembers.ReadString();
				Console.WriteLine(strLine);
				strLine = rdrMembers.ReadString();
				Console.WriteLine(strLine);
				strLine = rdrMembers.ReadString();
				Console.WriteLine(strLine);
			}
			finally
			{
				rdrMembers.Close();
				fstMembers.Close();
			}
		}
		catch(FileNotFoundException ex)
		{
			Console.Write("Error: " + ex.Message);
			Console.WriteLine(" May be the file doesn't exist or you typed it wrong!");
		}

		return 0;
	}
}

Here is an example of what this would produce:

Error: Could not find file "C:\Programs\MSVCS .NET 2003\Project1\bin\Debug\Assoc
iates.clb". May be the file doesn't exist or you typed it wrong!

IOException: As mentioned already, during file processing, anything could go wrong. If you don't know what caused an error, you can throw the IOException exception.

Practical LearningPractical Learning: Handling File Processing Exceptions

  1. To throw exceptions, change the file processing methods from the IceCream.cs file as follows:
     
    using System;
    using System.IO;
    
    namespace VendingMachine
    {
    	// This class is used to create and manage an ice cream
    	// and to process an order
    	sealed class IceCream
    	{
    
    		. . . No Change
    		
    		public void SaveOrder()
    		{
    			string NameOfFile;
    
    			Console.WriteLine("Please enter your initials or the name we will use to remember your order: ");
    			NameOfFile = Console.ReadLine();
    			NameOfFile = NameOfFile + ".icr";
    
    			try 
    			{
    				// Find out if the user entered a name of a file that is already in the machine
    				if( File.Exists(NameOfFile) )
    				{
    					char Answer;
    
    					FileStream stmIceCream = new FileStream(NameOfFile, FileMode.CreateNew);
    					BinaryWriter bnwIceCream = new BinaryWriter(stmIceCream);
    
    					try 
    					{
    						// 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 Cream Vending Machine =-=");
    							Console.WriteLine(" Saving Order: {0}", NameOfFile);
    							bnwIceCream.Write(Flavor[ChoiceFlavor-1]);
    							bnwIceCream.Write(Container[ChoiceContainer-1]);
    							bnwIceCream.Write(Ingredient[ChoiceIngredient-1]);
    							bnwIceCream.Write(Scoops);
    							bnwIceCream.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: ");
    							NameOfFile = Console.ReadLine();
    							NameOfFile = NameOfFile + ".icr";
    
    							try 
    							{
    								stmIceCream = new FileStream(NameOfFile, FileMode.CreateNew);
    								bnwIceCream = new BinaryWriter(stmIceCream);
    
    								Console.WriteLine("\n=-= Ice Cream Vending Machine =-=");
    								Console.WriteLine(" Saving Order: {0}", NameOfFile);
    								bnwIceCream.Write(Flavor[ChoiceFlavor-1]);
    								bnwIceCream.Write(Container[ChoiceContainer-1]);
    								bnwIceCream.Write(Ingredient[ChoiceIngredient-1]);
    								bnwIceCream.Write(Scoops);
    								bnwIceCream.Write(TotalPrice);
    							}
    							catch(IOException)
    							{
    								Console.Write("\nThe file you wanted us to create exists already. ");
    								Console.WriteLine("In case it was registered by a different customer, we will not delete it.");
    							}
    						}
    						else
    							Console.WriteLine("Invalid Answer - We will close.");
    					}
    					finally 
    					{
    						bnwIceCream.Close();
    						stmIceCream.Close();
    					}
    				}
    				else
    				{
    					FileStream stmIceCream = new FileStream(NameOfFile, FileMode.CreateNew);
    					BinaryWriter bnwIceCream = new BinaryWriter(stmIceCream);
    
    					try 
    					{
    						Console.WriteLine("\n=-= Ice Cream Vending Machine =-=");
    						Console.WriteLine(" Saving Order: {0}", NameOfFile);
    						bnwIceCream.Write(Flavor[ChoiceFlavor-1]);
    						bnwIceCream.Write(Container[ChoiceContainer-1]);
    						bnwIceCream.Write(Ingredient[ChoiceIngredient-1]);
    						bnwIceCream.Write(Scoops);
    						bnwIceCream.Write(TotalPrice);
    					}
    					catch(IOException)
    					{
    						Console.Write("\nThat file exists already. ");
    						Console.WriteLine("We need to preserve it just in case another customer will require it.");
    					}
    					finally 
    					{
    						bnwIceCream.Close();
    						stmIceCream.Close();
    					}
    				}
    			}
    			catch(IOException ex)
    			{
    				Console.WriteLine("\nError: " + ex.Message);
    				Console.WriteLine("Operation Canceled: The file you want to create exists already.");
    			}
    		}
    
    		public void OpenOrder()
    		{
    			string NameOfFile;
    		
    			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: ");
    			NameOfFile = Console.ReadLine();
    			NameOfFile = NameOfFile + ".icr";
    
    			try 
    			{
    				FileStream stmIceCream = new FileStream(NameOfFile, FileMode.Open);
    				BinaryReader bnrIceCream = new BinaryReader(stmIceCream);
    
    				try 
    				{
    					// Find out if this order was previously saved in the machine
    					if( File.Exists(NameOfFile) )
    					{
    						// If so, open it
    						SelectedFlavor = bnrIceCream.ReadString();
    						SelectedContainer = bnrIceCream.ReadString();
    						SelectedIngredient = bnrIceCream.ReadString();
    						Scoops = bnrIceCream.ReadInt32();
    						TotalPrice = bnrIceCream.ReadDecimal();
    
    						// And display it to the user
    						Console.WriteLine("\n=-= 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}\n", TotalPrice);
    					}
    					else
    						Console.WriteLine("The name you entered is not registered in our previous orders.");
    				}
    				finally 
    				{
    					bnrIceCream.Close();
    					stmIceCream.Close();
    				}
    			}
    			catch(FileNotFoundException ex)
    			{
    				Console.Write("\nError: " + ex.Message);
    				Console.WriteLine("It is unlikely that the file exists in our machine's register.");
    			}
    		}
    	}
    }
  2. Save it and switch to the Command Prompt
  3. Compile and exercise the exercise

Detailed Operations on Files

 

File Creation

Besides checking the existence of the file, the File class can be used to create a new file. To support this operation, the File class is equipped with the Create() method that is overloaded with two versions as follows:

public static FileStream Create(string path);
public static FileStream Create(string path, int buffersize);

In both cases, the File.Create() method returns a Stream value, in this case a FileStream value. As the File.Create() method indicates, it takes the name or path of the file as argument. If you know or want to specify the size, in bytes, of the file, you can use the second version.

To provide the same operation of creating a file, you can use the Open() method of the File class. It is overloaded in three versions as follows:

public static FileStream Open(
   string path,
   FileMode mode
);
public static FileStream Open(
   string path,
   FileMode mode,
   FileAccess access
);
public static FileStream Open(
   string path,
   FileMode mode,
   FileAccess access,
   FileShare share
);

 

Directories

 

Introduction

A directory is a section of a medium used to delimit a group of files. Because it is a "physical" area, it can handle operations not available on files. In fact, there are many fundamental differences between both:

  • A file is used to contain data. A directory doesn't contain data
  • A directory can contain one or more files and not vice-versa
  • A directory can contain other directories
  • A file can be moved from one directory to another. This operation is not possible vice-versa since a file cannot contain a directory

The similarities of both types are:

  • A directory or a file can be created. One of the restrictions is that two files cannot have the same name inside of the same directory. Two directories cannot have the same name inside of the same parent directory.
  • A directory or a file can be renamed. If a directory is renamed, the "path" of its files changes
  • A directory or a file can be deleted. If a directory is deleted, its files are deleted also
  • A directory or a file can be moved. If a directory moves, it "carries" all of its files to the new location
  • A directory or a file can be copied. One file can be copied from one directory to another. If a directory if copied to a new location, all of its files are also copied to the new location

Directory Operations

Before using a directory, you must first have it. You can use an existing directory if the operating system or someone else had already created one. You can also create a new directory. Directories are created and managed by various classes but the fundamental class is Directory. Additional operations are performed using the DirectoryInfo class.

Before using or creating a directory, you can first check if it exists. This is because, if a directory already exists in the location where you want to create it, you would be prevented from creating one with the same name. In the same way, if you just decide to directly use a directory that doesn't exist, the operation you want to perform may fail because the directory would not be found.

Before using or creating a directory, to check first whether it exists or not, you can call the Directory.Exists() Boolean method. Its syntax is:

public static bool Exists(string path);

This method receives the (complete) path of the directory. If the path is verified, the method returns true. If the directory exists, the method returns false.

To create a directory, you can call the CreateDirectory() method of the Directory class.

Object Serialization

 

Introduction

File processing is usually thought of as the technique of storing or retrieving bits of data of values from primitive variables that, when grouped, belong to a file. This approach falls short when the information dealt with is managed at a class level. Fortunately, modern libraries allow file processing on classes. In other words, a variable declared from a class can be saved to a stream and then the saved object can be retrieved later or on another computer. This the basis of object serialization. This serialization works by manipulating a whole object as its own value rather than its member variables.

The .NET Framework supports two types of object serialization: binary and XML.

Binary serialization works by processing an object rather than its member variables. This means that, to use it, you define an object and initialize it, or "fill" it, with the necessary values and any information you judge necessary. This creates a "state" of the object. It is this state that you prepare to serialize. When you save the object, it is converted into a stream.

XML Serialization

Thanks to its flexibility and platform independent way of dealing with values, XML is always a prima candidate for value serialization. Unlike strict object serialization, but like the techniques of file processing we reviewed earlier, XML considers the value members of an object, such as its fields and properties, for serialization. This means that XML doesn't allow serializing an object as its own value, but you can implement an effective object serialization by the way you proceed.

 

Previous Copyright © 2004-2006 FunctionX, Inc. Next