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
Practical
Learning: Introducing Directories |
|
- Start Microsoft Visual C# and create a Console
Application named GeorgetownCleaningServices5
- To create a new class, in the Solution Explorer, right-click
GeorgetownCleaningServices5
->
Add -> Class...
- Set the Name to Customer and click OK
- Change the file as follows:
using System;
namespace GeorgetownCleaningServices5
{
public class Customer
{
public string Name;
public string PhoneNumber;
}
}
|
- To create a new class, on the main menu, click Project -> Add Class...
- Set the Name to CleaningOrderDetails and press Enter
- Change the file as follows:
using System;
namespace GeorgetownCleaningServices5
{
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;
}
}
|
-
To save the project, on the Standard toolbar, click the Save All
button
- Accept all the defaults and click Save
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:
- 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
- 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
- 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.
- If the directory exists and there is a sub-directory specified under it,
the compiler would check its 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
- 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 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.
One of the most routine operations performed in a directory
consists of looking for a file. Both Microsoft Windows operating systems and the
users 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.
Practical
Learning: Using Directories and Files |
|
- To create a new class, in the Class View, right-click
GeorgetownCleaningOrder6 -> Add -> Class...
- Set the Name to CleaningDeposit and press Enter
- Change the file as follows:
using System;
using System.IO;
namespace GeorgetownCleaningServices5
{
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());
}
}
}
|
- To create a new class, in the Solution Explorer, right- click
GeorgetownCleaningOrder6 -> Add -> Class...
- Set the Name to CleaningRetrieval and press Enter
- Change the file as follows:
using System;
using System.IO;
namespace GeorgetownCleaningServices5
{
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");
}
public 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("====================================");
}
}
}
|
- Access the Program.cs file and change it as follows:
using System;
namespace GeorgetownCleaningServices6
{
class Program
{
static int 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();
return 0;
}
}
}
|
- 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 . . .
|
- Close the DOS window
- 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 . . .
|
- Remember the date you provided and close the DOS window
- 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 . . .
|
- Remember the date you provided and close the DOS window
- 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 . . .
|
- Close the DOS window
|
|