Home

Files Operations

   

Routine Operations on Files

 

Opening a File

As opposed to creating a file, probably the second most regular operation performed on a file consists of opening it to read or explore its contents. To support opening a file, the FileInfo class is equipped with the Open() method that is overloaded with three versions.

 

If you have a text-based file and want to directly read from it, you can use the StreamReader class that is equipped with the Read() and the ReadLine() methods. As done for the StreamWriter class, after using a StreamReader object, make sure you close it.

Deleting a File

If you have an existing file you don't need anymore, you can delete it. This operation can be performed by calling the FileInfo.Delete() method. Its syntax is:

public override void Delete();

Here is an example:

using System;
using System.IO;

public class Program
{
    static int Main(string[] args)
    {
        var fleMembers = new FileInfo("First.txt");

        if (fleMembers.Exists == true)
            fleMembers.Delete();

        return 0;
    }
}
 

Copying a File

You can make a copy of a file from one directory to another. To do this, you can call the FileInfo.CopyTo() method that is overloaded with two versions. The first version has the following syntax:

public FileInfo CopyTo(string destFileName);

When calling this method, specify the path or directory that will be the destination of the copied file. Here is an example:

using System;
using System.IO;

public class Program
{
    static int Main(string[] args)
    {
        var fleMembers = new FileInfo("Reality.txt");
        var strMyDocuments =
            Environment.GetFolderPath(Environment.SpecialFolder.Personal);

        if (fleMembers.Exists == true)
            fleMembers.CopyTo(string.Concat(strMyDocuments, "\\Federal.txt"));

        return 0;
    }
}

In this example, a file named Reality.txt in the directory of the project would be retrieved and its content would be applied to a new file named Federal.txt created in the My Documents folder of the current user.

When calling the first version of the FileInfo.CopyTo() method, if the file exists already, the operation would not continue and you would simply receive a message box. If you insist, you can overwrite the target file. To do this, you can use the second version of this method. Its syntax is:

public FileInfo CopyTo(string destFileName, bool overwrite);

The first argument is the same as that of the first version of the method. The second argument specifies what action to take if the file exists already in the target directory. If you want to overwrite it, pass the argument as true; otherwise, pass it as false.

Moving a File

If you copy a file from one directory to another, you would have two copies of the same file or the same contents in two files. Instead of copying, if you want, you can simply move the file from one directory to another. This operation can be performed by calling the FileInfo.MoveTo() method. Its syntax is:

public void MoveTo(string destFileName);

The argument to this method is the same as that of the CopyTo() method. After executing this method, the FileInfo object would be moved to the destFileName path.

Here is an example:

using System;
using System.IO;

public class Program
{
    static int Main(string[] args)
    {
        var fleMembers = new FileInfo("pop.txt");
        var strMyDocuments =
            Environment.GetFolderPath(Environment.SpecialFolder.Personal);

        if (fleMembers.Exists == true)
            fleMembers.MoveTo(string.Concat(strMyDocuments, "\\Federal.txt"));

        return 0;
    }
}

Characteristics of a File

 

The Date and Time a File Was Created 

To keep track of it, after a file has been created, the operating system makes a note of the date and the time the file was created. This information can be valuable in other operations such as search routines. You too are allowed to change this date and time values to those you prefer.

As mentioned already, the OS makes sure to keep track of the date and time a file was created. To find out what those date and time values are, you can access the FileSystemInfo.CreationTime property. This would be done as follows:

using System;
using System.IO;

public class Program
{
    static int Main(string[] args)
    {
        var someFile = new FileInfo("First.txt");
        DateTime dteCreationTime = someFile.CreationTime;

        if (someFile.Exists == true)
            Console.WriteLine("Date and Time Created: " +
                dteCreationTime.ToString());

        return 0;
    }
}

Of course, by entering the appropriate format in the parentheses of the ToString() method, you can get only either the date or only the time.

If you don't like the date, the time, or both, that the OS would have set when the file was created, you can change them. To change one or both of these values, you can assign a desired DateTime object to the FileSystemInfo.set_CreationTime() property.

The Date and Time a File Was Last Accessed 

Many applications allow a user to open an existing file and to modify it. When people work in a team or when a particular file is regularly opened, at one particular time, you may want to know the date and time that the file was last accessed. To get this information, you can access the FileSystemInfo.LastAccessTime property.

If you are interested to know the last date and time a file was modified, you can get the value of its FileSystemInfo.LastWriteTime property.

The Name of a File

The operating system requires that each file have a name. In fact, the name must be specified when creating a file. This allows the OS to catalogue the computer files. This also allows you to locate or identify a particular file you need.

When reviewing or opening a file, to get its name, the FileInfo class is equipped with the Name property. Here is an example:

using System;
using System.IO;

public class Program
{
    static int Main(string[] args)
    {
        var someFile = new FileInfo("Persons.spr");

        if (someFile.Exists == true)
            Console.WriteLine("The name of this file is: \"" + 
		someFile.Name + "\"");

        return 0;
    }
}

This string simply identifies a file.

The Extension of a File

With the advent of Windows 95 and later, the user doesn't have to specify the extension of a file when creating it. Because of the type of confusion that this can lead to, most applications assist the user with this detail. Some applications allow the user to choose among various extensions. For example, using Notepad, a user can open a text, a PHP, a script, or an HTML file.

When you access a file or when the user opens one, to know the extension of the file, you can access the value of the FileSystemInfo.Extension property. Here is an example:

using System;
using System.IO;

public class Program
{
    static int Main(string[] args)
    {
        var someFile = new FileInfo("Persons.spr");

        if (someFile.Exists == true)
            Console.WriteLine("File Extension: " + someFile.Extension);

        return 0;
    }
}

This would produce:

File Extension: .spr
Press any key to continue . . .

The Size of a File

One of the routine operations the operating system performs consists of calculating the sizes of files it holds. This information is provided in terms of bits, kilobits, or kilobytes. To get the size of a file, the FileInfo class is quipped with the Length property. Here is an example of accessing it:

using System;
using System.IO;

public class Program
{
    static int Main(string[] args)
    {
        var someFile = new FileInfo("Persons.spr");

        if (someFile.Exists == true)
            Console.WriteLine("File Size: " + 
                someFile.Length.ToString());

        return 0;
    }
}

Here is an example of what this would produce:

File Size: 57
Press any key to continue . . .

The Path to a File

Besides the name of the file, it must be located somewhere. The location of a file is referred to as its path or directory. The FileInfo class represents this path as the DirectoryName property. Therefore, if a file has already been created, to get its path, you can access the value of the FileInfo.DirectoryName property.

Besides the FileInfo.Directoryname, to know the full path to a file, you can access its FileSystemInfo.FullName property.

The Attributes of a File

Attributes are characteristics that apply to a file, defining what can be done or must be disallowed on it. The Attributes are primarily defined by, and in, the operating system, mostly when a file is created. When the user accesses or opens a file, to get its attributes, you can access the value of its FileSystemInfo.Attributes property. This property produces a FileAttributes object.

When you create or access a file, you can specify or change some of the attributes. To do this, you can a FileAttributes object and assign it to the FileSystemInfo.Attributes property.

FileAttributes is an enumeration with the following members: Archive, Compressed, Device, Directory, Encrypted, Hidden, Normal, NotContentIndexed, Offline, ReadOnly, ReparsePoint, SparseFile, System, and Temporary.

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 file(s) 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. A file can be copied from one directory to another. If a directory is copied to a new location, all of its files are also copied to the new location

ApplicationApplication: Introducing Directories

  1. Start Microsoft Visual Studio and create a Console Application named GeorgetownDryCleaningServices6
  2. To create a new class, in the Solution Explorer, right-click GeorgetownDryCleaningServices6 -> Add -> Class...
  3. Set the Name to Customer and click OK
  4. Change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace GeorgetownDryCleaningServices6
    {
        public class Customer
        {
            public string Name;
            public string PhoneNumber;
        }
    }
  5. To create a new class, on the main menu, click Project -> Add Class...
  6. Set the Name to CleaningOrderDetails and press Enter
  7. Change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace GeorgetownDryCleaningServices6
    {
        public sealed class CleaningOrderDetails
        {
            // The date the cleaning items were deposited
            public DateTime OrderDate;
            public DateTime OrderTime;
            // Numbers to represent cleaning items
            public uint numberOfShirts;
            public uint numberOfPants;
            public uint NumberOtherItems;
    
            // Price of items
            public decimal priceOneShirt = 0.95M;
            public decimal priceAPairOfPants = 2.95M;
            public decimal priceOtherItems = 4.55M;
            public decimal TaxRate = 0.0575M;  // 5.75%
    
            // Each of these sub totals will be used for cleaning items
            public decimal SubTotalShirts;
            public decimal SubTotalPants;
            public decimal SubTotalOtherItems;
    
            // Values used to process an order
            public decimal TotalOrder;
            public decimal TaxAmount;
            public decimal SalesTotal;
        }
    }
  8. To save the project, on the Standard toolbar, click the Save All button Save All
  9. Accept all the defaults and click Save

Directory Creation

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. Directory is a static class, which means all of its methods are static, which means you will never need to declare an instance of the Directory class in order to use it.

Besides the Directory class, additional operations of folders and sub-folders can be performed using the DirectoryInfo class.

To create a directory, you can call the CreateDirectory() method of the Directory class. This method is available in two versions. One of the versions uses the following syntax:

public static DirectoryInfo CreateDirectry(string path);

This method takes as argument the (complete) path of the desired directory. Here is an example:

E:\Programs\Business Orders\Customer Information

When this method is called:

  1. It first checks the parent drive, in this case E.
    If the drive doesn't exist, because this method cannot create a drive, the compiler would throw a DirectoryNotFoundException exception
  2. If the drive (in this case E) exists, the compiler moves to the first directory part of the path; in this case this would be the Programs folder in the E drive.
    If the folder doesn't exist, the compiler would create it. If that first director doesn't exist, this means that the other directory(ies), if any, under the first don't exist. So, the compiler would create it/them
  3. If the first directory exists and if there is no other directory under that directory, the compiler would stop and would not do anything further.
  4. If the directory exists and there is a sub-directory specified under it, the compiler would check the existence of that directory.
    If the sub-directory exists, the compiler would not do anything further and would stop.
    If the sub-directory doesn't exist, the compiler would create it
  5. The compiler would repeat step 4 until the end of the specified path

The Directory.CreateDirectory() method returns a DirectoryInfo object that you can use as you see fit.

Checking for a Directory Existence

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 first check 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 exists, the method returns true. If the directory doesn't exist, the method returns false.

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

Locating a File

One of the most routine operations performed in a directory consists of looking for a file. Both Microsoft Windows operating systems and the user's intuition have different ways of addressing this issue. The .NET Framework also provides its own means of performing this operation, through various techniques. You can start by checking the sub-directories and files inside of a main directory.

To look for files in a directory, the DirectoryInfo class can assist you with its GetFiles() method, which is overloaded with three versions.

ApplicationApplication: Using Directories and Files

  1. To create a new class, in the Class View, right-click GeorgetownCleaningOrder6 -> Add -> Class...
  2. Set the Name to CleaningDeposit and press Enter
  3. Change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    
    namespace GeorgetownDryCleaningServices6
    {
        public abstract class CustomerOrder
        {
            public abstract void ProcessOrder();
            public abstract void ShowReceipt();
        }
    
        public class CleaningDeposit : CustomerOrder
        {
            private Customer custInfo;
            public CleaningOrderDetails depot;
            private decimal AmountTended;
            private decimal Difference;
    
            public CleaningDeposit()
            {
                this.custInfo = new Customer();
                this.depot = new CleaningOrderDetails();
            }
    
            private Customer IdentifyCustomer()
            {
                string strCustomerName;
                string strTelephoneNumber, strPhoneFormatted;
    
                Console.Write("Enter Customer Phone Number: ");
                strTelephoneNumber = Console.ReadLine();
    
                // Remove the spaces, parentheses, if any, and dashes, if any
                strTelephoneNumber = strTelephoneNumber.Replace(" ", "");
                strTelephoneNumber = strTelephoneNumber.Replace("(", "");
                strTelephoneNumber = strTelephoneNumber.Replace(")", "");
                strTelephoneNumber = strTelephoneNumber.Replace("-", "");
                if (strTelephoneNumber.Length != 10)
                {
                    Console.WriteLine("Invalid telphone number: {0} " +
                                      "characters instead of 10 digits",
                                      strTelephoneNumber.Length);
                    return null;
                }
                strPhoneFormatted = "(" + strTelephoneNumber.Substring(0, 3) +
                                    ") " + strTelephoneNumber.Substring(3, 3) +
                                    "-" + strTelephoneNumber.Substring(6, 4);
    
                string strFilename = strTelephoneNumber + @".gcs";
                string strPath = @"C:\Georgetown Cleaning Services\Customers\" +
                                 @"\" + strFilename;
    
                if (File.Exists(strPath))
                {
                    FileStream stmCustomer =
                        File.Open(strPath, FileMode.Open, FileAccess.Read);
                    BinaryReader bnrCustomer = new BinaryReader(stmCustomer);
    
                    custInfo.Name = bnrCustomer.ReadString();
                    custInfo.PhoneNumber = bnrCustomer.ReadString();
    
                    Console.WriteLine("\n=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
                    Console.WriteLine("-/- Georgetown Cleaning Services -/-");
                    Console.WriteLine("------------------------------------");
                    Console.WriteLine("Customer Name: {0}", custInfo.Name);
                    Console.WriteLine("Phone Number:  {0}", custInfo.PhoneNumber);
                    Console.WriteLine("------------------------------------\n");
                }
                else // If the customer information was not found in a file
                {
                    Console.WriteLine("It looks like this is the first time you " +
                                      "are trusting  us with your cleaning order");
    		Directory.CreateDirectory(@"C:\Georgetown Cleaning Services\Customers");
                    FileStream stmCustomer = File.Create(strPath);
                    BinaryWriter bnwCustomer =
                        new BinaryWriter(stmCustomer);
                    Console.Write("Enter Customer Name: ");
                    strCustomerName = Console.ReadLine();
                    bnwCustomer.Write(strCustomerName);
                    bnwCustomer.Write(strPhoneFormatted);
    
                    custInfo.Name = strCustomerName;
                    custInfo.PhoneNumber = strTelephoneNumber;
                }
    
                return custInfo;
            }
    
            public override void ProcessOrder()
            {
                Console.WriteLine("-/- Georgetown Cleaning Services -/-");
                Customer client = this.IdentifyCustomer();
    
                try
                {
                    Console.Write("Enter the order date(mm/dd/yyyy):  ");
                    this.depot.OrderDate = DateTime.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("The value you entered is not a valid date");
                }
                try
                {
                    Console.Write("Enter the order time(hh:mm AM/PM): ");
                    this.depot.OrderTime = DateTime.Parse(Console.ReadLine());
                }
                catch
                {
                    Console.WriteLine("The value you entered is not a valid time");
                }
    
                // Request the quantity of each category of items
                try
                {
                    Console.Write("Number of Shirts:      ");
                    this.depot.numberOfShirts =
                        uint.Parse(Console.ReadLine());
                    if (this.depot.numberOfShirts < uint.MinValue)
                        throw new OverflowException("Negative value not " +
                                                    "allowed for shirts");
                }
                catch (FormatException)
                {
                    Console.WriteLine("The value you typed for the number of " +
                                      "shirts is not a valid number");
                }
                try
                {
                    Console.Write("Number of Pants:       ");
                    this.depot.numberOfPants =
                        uint.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("The value you typed for the number of " +
                                      "pair or pants is not a valid number");
                }
                try
                {
                    Console.Write("Number of Other Items: ");
                    this.depot.NumberOtherItems = uint.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("The value you typed for the number of " +
                                      "other items is not a valid number");
                }
                // Perform the necessary calculations
                this.depot.SubTotalShirts =
                    this.depot.numberOfShirts * this.depot.priceOneShirt;
                this.depot.SubTotalPants =
                    this.depot.numberOfPants * this.depot.priceAPairOfPants;
                this.depot.SubTotalOtherItems =
                    this.depot.NumberOtherItems * this.depot.priceOtherItems;
                // Calculate the "temporary" total of the order
                this.depot.TotalOrder = this.depot.SubTotalShirts +
                                        this.depot.SubTotalPants +
                                        this.depot.SubTotalOtherItems;
    
                // Calculate the tax amount using a constant rate
                this.depot.TaxAmount = this.depot.TotalOrder * this.depot.TaxRate;
                // Add the tax amount to the total order
                this.depot.SalesTotal = this.depot.TotalOrder + this.depot.TaxAmount;
    
                // Communicate the total to the user...
                Console.WriteLine("\nThe Total order is: {0:C}", this.depot.SalesTotal);
                // and request money for the order
                try
                {
                    Console.Write("Amount Tended? ");
                    AmountTended = decimal.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("You were asked to enter an " +
                                      "amount of money but...");
                }
                // Calculate the difference owed to the customer
                // or that the customer still owes to the store
                Difference = AmountTended - this.depot.SalesTotal;
    
                this.ShowReceipt();
                this.Save();
            }
    
            public override void ShowReceipt()
            {
                Console.WriteLine();
                // Display the receipt
                Console.WriteLine("====================================");
                Console.WriteLine("-/- Georgetown Cleaning Services -/-");
                Console.WriteLine("====================================");
                Console.WriteLine("Customer:    {0}", this.custInfo.Name);
                Console.WriteLine("Home Phone:  {0}", this.custInfo.PhoneNumber);
                Console.WriteLine("Order Date:  {0:D}", this.depot.OrderDate);
                Console.WriteLine("Order Time:  {0:t}", this.depot.OrderTime);
                Console.WriteLine("------------------------------------");
                Console.WriteLine("Item Type    Qty Unit/Price Sub-Total");
                Console.WriteLine("------------------------------------");
                Console.WriteLine("Shirts      {0,3}   {1,4}      {2,6}",
                                  this.depot.numberOfShirts,
                                  this.depot.priceOneShirt,
                                  this.depot.SubTotalShirts);
                Console.WriteLine("Pants       {0,3}   {1,4}      {2,6}",
                                 this.depot.numberOfPants,
                                 this.depot.priceAPairOfPants,
                                 this.depot.SubTotalPants);
                Console.WriteLine("Other Items {0,3}   {1,4}      {2,6}",
                                  this.depot.NumberOtherItems,
                                  this.depot.priceOtherItems,
                                  this.depot.SubTotalOtherItems);
                Console.WriteLine("------------------------------------");
                Console.WriteLine("Total Order:   {0,6}",
                                  this.depot.TotalOrder.ToString("C"));
                Console.WriteLine("Tax Rate:      {0,6}",
                                  this.depot.TaxRate.ToString("P"));
                Console.WriteLine("Tax Amount:    {0,6}",
                                  this.depot.TaxAmount.ToString("C"));
                Console.WriteLine("Net Price:     {0,6}",
                                  this.depot.SalesTotal.ToString("C"));
                Console.WriteLine("------------------------------------");
                Console.WriteLine("Amount Tended: {0,6}",
                                  AmountTended.ToString("C"));
                Console.WriteLine("Difference:    {0,6}",
                                  Difference.ToString("C"));
                Console.WriteLine("====================================");
            }
    
            public virtual void Save()
            {
                string strPhoneNumber = this.custInfo.PhoneNumber;
    
                // Remove the spaces, parentheses, and dashes
                strPhoneNumber = strPhoneNumber.Replace(" ", "");
                strPhoneNumber = strPhoneNumber.Replace("(", "");
                strPhoneNumber = strPhoneNumber.Replace(")", "");
                strPhoneNumber = strPhoneNumber.Replace("-", "");
    
                string strMonth = depot.OrderDate.Month.ToString();
                if (depot.OrderDate.Month < 10)
                    strMonth = "0" + strMonth;
    
                string strDay = depot.OrderDate.Day.ToString();
                if (depot.OrderDate.Day < 10)
                    strDay = "0" + strDay;
    
                string strYear = depot.OrderDate.Year.ToString();
    
                string strFilename = strMonth + strDay + strYear + @".gcs";
    
                string strPath = @"C:\Georgetown Cleaning Services\Cleaning Orders\" +
                                 @"\" + strPhoneNumber + @"\" + strFilename;
    
    	    Directory.CreateDirectory(@"C:\Georgetown Cleaning Services\Cleaning Orders\"
                                          + strPhoneNumber);
    
                FileStream stmCleaningOrder = File.Create(strPath);
                BinaryWriter bnwCleaningOrder =
                    new BinaryWriter(stmCleaningOrder);
    
                bnwCleaningOrder.Write(this.custInfo.Name);
                bnwCleaningOrder.Write(this.custInfo.PhoneNumber);
                bnwCleaningOrder.Write(this.depot.OrderDate.ToString());
                bnwCleaningOrder.Write(this.depot.OrderTime.ToString());
                bnwCleaningOrder.Write(this.depot.numberOfShirts.ToString());
                bnwCleaningOrder.Write(this.depot.numberOfPants.ToString());
                bnwCleaningOrder.Write(this.depot.NumberOtherItems.ToString());
                bnwCleaningOrder.Write(this.depot.priceOneShirt.ToString());
                bnwCleaningOrder.Write(this.depot.priceAPairOfPants.ToString());
                bnwCleaningOrder.Write(this.depot.priceOtherItems.ToString());
                bnwCleaningOrder.Write(this.depot.TaxRate.ToString());
                bnwCleaningOrder.Write(this.depot.SubTotalShirts.ToString());
                bnwCleaningOrder.Write(this.depot.SubTotalPants.ToString());
                bnwCleaningOrder.Write(this.depot.SubTotalOtherItems.ToString());
                bnwCleaningOrder.Write(this.depot.TotalOrder.ToString());
                bnwCleaningOrder.Write(this.depot.TaxAmount.ToString());
                bnwCleaningOrder.Write(this.depot.SalesTotal.ToString());
            }
        }
    }
  4. To create a new class, in the Solution Explorer, right- click GeorgetownCleaningOrder6 -> Add -> Class...
  5. Set the Name to CleaningRetrieval and press Enter
  6. Change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    
    namespace GeorgetownDryCleaningServices6
    {
        public class CleaningRetrieval
        {
            private Customer custInfo;
            private CleaningOrderDetails depot;
            private string strPhoneNumber;
    
            public CleaningRetrieval()
            {
                this.custInfo = new Customer();
                this.depot = new CleaningOrderDetails();
            }
    
            public virtual void Open()
            {
                Console.Write("Enter Receipt Number: ");
                string strFilename = Console.ReadLine();
    
                string strPath = @"C:\Georgetown Cleaning Services\Cleaning Orders\" +
                                 @"\" + strFilename + @"\" + strFilename + ".gcs";
    
                DirectoryInfo di =
             new DirectoryInfo(@"C:\Georgetown Cleaning Services\Cleaning Orders");
                FileInfo[] aryFiles = di.GetFiles("*", SearchOption.AllDirectories);
    
                string strFileFullname = "";
                bool found = false;
    
                foreach (FileInfo fle in aryFiles)
                {
                    if (fle.Name == (strFilename + ".gcs"))
                    {
                        found = true;
                        strFileFullname = fle.FullName;
                    }
                }
    
                if (found == true)
                {
                    FileStream stmCleaningOrder =
                                       File.Open(strFileFullname,
                                                 FileMode.Open,
                                                 FileAccess.Read);
                    BinaryReader bnrCleaningOrder = new BinaryReader(stmCleaningOrder);
                    this.custInfo.Name = bnrCleaningOrder.ReadString();
                    this.custInfo.PhoneNumber = bnrCleaningOrder.ReadString();
                    this.depot.OrderDate = DateTime.Parse(bnrCleaningOrder.ReadString());
                    this.depot.OrderTime = DateTime.Parse(bnrCleaningOrder.ReadString());
                    this.depot.numberOfShirts = uint.Parse(bnrCleaningOrder.ReadString());
                    this.depot.numberOfPants = uint.Parse(bnrCleaningOrder.ReadString());
                    this.depot.NumberOtherItems = 
    			uint.Parse(bnrCleaningOrder.ReadString());
                    this.depot.priceOneShirt = 
    			decimal.Parse(bnrCleaningOrder.ReadString());
                    this.depot.priceAPairOfPants = 
    			decimal.Parse(bnrCleaningOrder.ReadString());
                    this.depot.priceOtherItems = 
    			decimal.Parse(bnrCleaningOrder.ReadString());
                    this.depot.TaxRate = decimal.Parse(bnrCleaningOrder.ReadString());
                    this.depot.SubTotalShirts = 
    			decimal.Parse(bnrCleaningOrder.ReadString());
                    this.depot.SubTotalPants = 
    			decimal.Parse(bnrCleaningOrder.ReadString());
                    this.depot.SubTotalOtherItems = 
    			decimal.Parse(bnrCleaningOrder.ReadString());
                    this.depot.TotalOrder = decimal.Parse(bnrCleaningOrder.ReadString());
                    this.depot.TaxAmount = decimal.Parse(bnrCleaningOrder.ReadString());
                    this.depot.SalesTotal = decimal.Parse(bnrCleaningOrder.ReadString());
    
                    this.strPhoneNumber = "(" + 
    				      this.custInfo.PhoneNumber.Substring(0, 3) +
                                          ") " + 
    				      this.custInfo.PhoneNumber.Substring(3, 3) +
                                          "-" + 
    				      this.custInfo.PhoneNumber.Substring(6, 4);
                    this.ShowReceipt();
                }
                else
                    Console.WriteLine("No cleaning order of " +
    				  "that receipt number was found");
            }
    
            internal void ShowReceipt()
            {
                Console.WriteLine();
                // Display the receipt
                Console.WriteLine("====================================");
                Console.WriteLine("-/- Georgetown Cleaning Services -/-");
                Console.WriteLine("====================================");
                Console.WriteLine("Customer:    {0}", this.custInfo.Name);
                Console.WriteLine("Home Phone:  {0}", this.custInfo.PhoneNumber);
                Console.WriteLine("Order Date:  {0:D}", this.depot.OrderDate);
                Console.WriteLine("Order Time:  {0:t}", this.depot.OrderTime);
                Console.WriteLine("------------------------------------");
                Console.WriteLine("Item Type   Qty Unit/Price Sub-Total");
                Console.WriteLine("------------------------------------");
                Console.WriteLine("Shirts      {0,3}   {1,4}      {2,6}",
                                  this.depot.numberOfShirts,
                                  this.depot.priceOneShirt,
                                  this.depot.SubTotalShirts);
                Console.WriteLine("Pants       {0,3}   {1,4}      {2,6}",
                                 this.depot.numberOfPants,
                                 this.depot.priceAPairOfPants,
                                 this.depot.SubTotalPants);
                Console.WriteLine("Other Items {0,3}   {1,4}      {2,6}",
                                  this.depot.NumberOtherItems,
                                  this.depot.priceOtherItems,
                                  this.depot.SubTotalOtherItems);
                Console.WriteLine("------------------------------------");
                Console.WriteLine("Total Order:   {0,6}",
                                  this.depot.TotalOrder.ToString("C"));
                Console.WriteLine("Tax Rate:      {0,6}",
                                  this.depot.TaxRate.ToString("P"));
                Console.WriteLine("Tax Amount:    {0,6}",
                                  this.depot.TaxAmount.ToString("C"));
                Console.WriteLine("Net Price:     {0,6}",
                                  this.depot.SalesTotal.ToString("C"));
                Console.WriteLine("====================================");
            }
        }
    }
  7. Access the Program.cs file and change it as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace GeorgetownDryCleaningServices6
    {
        public class Program
        {
            static void Main(string[] args)
            {
                char answer = 'q';
    
                Console.WriteLine("Is this a new order or the customer is " +
                                  "retrieving items previously left for cleaning?");
                Console.WriteLine("0. Quit");
                Console.WriteLine("1. This is a new order");
                Console.WriteLine("2. The customer is retrieving an existing order");
                Console.Write("Your Choice: ");
                answer = char.Parse(Console.ReadLine());
    
                switch (answer)
                {
                    case '1':
                        CleaningDeposit depotOrder = new CleaningDeposit();
                        depotOrder.ProcessOrder();
                        break;
    
                    case '2':
                        CleaningRetrieval previousOrder = new CleaningRetrieval();
                        previousOrder.Open();
                        break;
    
                    default:
                        break;
                }
    
                Console.WriteLine();
            }
        }
    }
  8. Execute the application and test it. Here is an example:
    Is this a new order or the customer is retrieving 
    items previously left for cleaning?
    0. Quit
    1. This is a new order
    2. The customer is retrieving an existing order
    Your Choice: 0
    
    Press any key to continue . . .
  9. Close the DOS window
  10. Execute the application and create a new order. Here is an example:
    Is this a new order or the customer is retrieving 
    items previously left for cleaning?
    0. Quit
    1. This is a new order
    2. The customer is retrieving an existing order
    Your Choice: 1
    -/- Georgetown Cleaning Services -/-
    Enter Customer Phone Number: 202 103 0443
    It looks like this is the first time you are trusting 
    us with your cleaning order
    Enter Customer Name: Arsene Cranston
    Enter the order date(mm/dd/yyyy):  11/20/2006
    Enter the order time(hh:mm AM/PM): 08:12 AM
    Number of Shirts:      6
    Number of Pants:       4
    Number of Other Items: 2
    
    The Total order is: $28.13
    Amount Tended? 30
    
    ====================================
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:    Arsene Cranston
    Home Phone:  2021030443
    Order Date:  Monday, November 20, 2006
    Order Time:  8:12 AM
    ------------------------------------
    Item Type    Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts        6   0.95        5.70
    Pants         4   2.95       11.80
    Other Items   2   4.55        9.10
    ------------------------------------
    Total Order:   $26.60
    Tax Rate:      5.75 %
    Tax Amount:     $1.53
    Net Price:     $28.13
    ------------------------------------
    Amount Tended: $30.00
    Difference:     $1.87
    ====================================
    
    Press any key to continue . . .
  11. Remember the date you provided and close the DOS window
  12. Execute the application and create a new order. Here is an example:
    Is this a new order or the customer is retrieving items 
    previously left for cleaning?
    0. Quit
    1. This is a new order
    2. The customer is retrieving an existing order
    Your Choice: 1
    -/- Georgetown Cleaning Services -/-
    Enter Customer Phone Number: 301-022-1077
    It looks like this is the first time you are trusting 
    us with your cleaning order
    Enter Customer Name: Helene Craft
    Enter the order date(mm/dd/yyyy):  11/21/2006
    Enter the order time(hh:mm AM/PM): 9:25
    Number of Shirts:      3
    Number of Pants:       0
    Number of Other Items: 5
    
    The Total order is: $27.07
    Amount Tended? 40
    
    ====================================
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:    Helene Craft
    Home Phone:  3010221077
    Order Date:  Tuesday, November 21, 2006
    Order Time:  9:25 AM
    ------------------------------------
    Item Type    Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts        3   0.95        2.85
    Pants         0   2.95        0.00
    Other Items   5   4.55       22.75
    ------------------------------------
    Total Order:   $25.60
    Tax Rate:      5.75 %
    Tax Amount:     $1.47
    Net Price:     $27.07
    ------------------------------------
    Amount Tended: $40.00
    Difference:    $12.93
    ====================================
    
    Press any key to continue . . .
  13. Remember the date you provided and close the DOS window
  14. Execute the application and choose to open an existing order. Here is an example:
    Is this a new order or the customer is retrieving 
    items previously left for cleaning?
    0. Quit
    1. This is a new order
    2. The customer is retrieving an existing order
    Your Choice: 2
    Enter Receipt Number: 11202006
    
    ====================================
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:    Arsene Cranston
    Home Phone:  2021030443
    Order Date:  Monday, November 20, 2006
    Order Time:  8:12 AM
    ------------------------------------
    Item Type   Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts        6   0.95        5.70
    Pants         4   2.95       11.80
    Other Items   2   4.55        9.10
    ------------------------------------
    Total Order:   $26.60
    Tax Rate:      5.75 %
    Tax Amount:     $1.53
    Net Price:     $28.13
    ====================================
    
    Press any key to continue . . .
  15. Close the DOS window
 

Previous Copyright © 2010-2016, FunctionX Home