A directory is a section of a medium (floppy disc, flash drive, hard drive, CD, DVD, etc) 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

Practical LearningPractical Learning: Introducing Directories

  1. Start Microsoft Visual Studio
  2. To create a new application, on the main menu, click File -> New Project...
  3. In the middle list, click Windows Forms Application
  4. Set the name to WattsALoan2
  5. Click OK
  6. To create a new form, on the main menu, click Project -> Add New Item...
  7. In the middle list, click Windows Form
  8. Set the Name to NewEmployee
  9. Click Add
  10. Design the form as follows:
    Control Text Name
    Label Label Employee #:  
    TextBox TextBox   txtEmployeeNumber
    Label Label Employee Name:  
    TextBox TextBox   txtEmployeeName
    Button TextBox Create btnCreate
    Button TextBox Close btnClose
  11. Double-click the Close button
  12. In the top section of the file, under the using namespace lines, type
    using namespace System::IO;
  13. Implement its event as follows:
    System::Void btnClose_Click(System::Object^  sender, System::EventArgs^  e)
  14. Display the first form
  15. In the Common Controls section of the Toolbox, click ToolTip and click the form
  16. Design the form as follows:
    Watts A Loan
    Control Name Text ToolTip on toolTip1
    Label Label   If this is a new loan, enter a new account number and the name of the customer who is requesting the loan  
    Label Label   To open a previously prepared loan, enter its account number and press Tab  
    Label Label   Acnt #:  
    Label Label   Customer Name:  
    Label Label   Customer:  
    TextBox TextBox txtAccountNumber   Account number of the customer requesting the loan
    TextBox TextBox txtCustomerName   Name of the customer requesting the loan
    Label Label   Empl #:  
    Label Label   Employee Name:  
    Label Label   Prepared By:  
    TextBox TextBox txtEmployeeNumber   Employee number of the clerk preparing the loan
    TextBox TextBox txtEmployeeName   Name of the clerk preparing the loan
    Button Button btnNewEmployee   Used to add a new employee to the company
    Button Button btnNewCustomer   Used to create an account for a new customer
    Label Label   Loan Amount:  
    TextBox TextBox txtLoanAmount   Amount of loan the customer is requesting
    Label Label   Interest Rate:  
    TextBox TextBox txtInterestRate   Annual percentage rate of the loan
    Label Label   %  
    Label Label   Periods  
    TextBox TextBox   txtPeriods The number of months the loan is supposed to last
    Button Button btnCalculate Calculate Used to calculate the monthly payment
    Label Label   Monthly Payment:  
    TextBox TextBox txtMonthlyPayment   The minimum amount the customer should pay every month
    Button Button btnClose Close Used to close the form
  17. Double-click the Calculate button and implement its event as follows:
    System::Void btnCalculate_Click(System::Object^  sender, System::EventArgs^  e)
        double Principal    = 0.00,
               InterestRate = 0.00,
        double Periods = 0.00;
        try {
            Principal = double::Parse(txtLoanAmount->Text);
        catch(FormatException ^)
            MessageBox::Show(L"The value you entered for the "
                             L"principal is not valid");
        try {
            InterestRate = double::Parse(txtInterestRate->Text);
        catch(FormatException ^)
            MessageBox::Show(L"Wrong Value: The interest rate must "
                             L"be a value between 0 and 100");
        try {
            Periods = double::Parse(txtPeriods->Text);
        catch(FormatException ^)
            MessageBox::Show(L"You entered an invalid value for the periods");
        double I = InterestRate / 100;
        double p = Periods / 12;
    	InterestEarned = Principal * I  * p;
        FutureValue    = Principal + InterestEarned;
    	MonthlyPayment = FutureValue / Periods;
        txtMonthlyPayment->Text = MonthlyPayment.ToString(L"F");
  18. Return to the form and double-click the Close button to implement its event as follows:
    System::Void btnClose_Click(System::Object^  sender, System::EventArgs^  e)
  19. Scroll up completely and type the following lines
    #pragma once
    #include "NewEmployee.h"
    namespace WattsALoan2 {
    	using namespace System;
    	using namespace System::ComponentModel;
    	using namespace System::Collections;
    	using namespace System::Windows::Forms;
    	using namespace System::Data;
    	using namespace System::Drawing;
    	using namespace System::IO;
  20. Scroll down and implement the event as follows:
    System::Void btnNewEmployee_Click(System::Object^  sender, System::EventArgs^  e)
        NewEmployee ^ frmNewEmployee = gcnew NewEmployee;
  21. Return to the form



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 an abstract and sealed class. All of its member functions 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() member function of the Directory class. This member function is available in two versions. One of the versions uses the following syntax:

    static DirectoryInfo ^ CreateDirectry(String ^path);

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

E:\Programs\Business Orders\Customer Information

When this member function is called:

  1. It first checks the parent drive, in this case E.
    If the drive doesn't exist, because this member function 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() member function returns a DirectoryInfo object that you can use as you see fit.

Practical LearningPractical Learning: Creating a Directory

  1. On the (main) form, double-click an unoccupied area of its body
  2. Implement its Load event as follows:
    System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e)
    	 String ^ strDirectory = L"C:\\Watts A Loan";
    	 if( !Directory::Exists(strDirectory) )
    	 String ^ strFilename = strDirectory + L"\\Employees.wal";
    	 FileInfo ^ fiEmployees = gcnew FileInfo(strFilename);
    	 // If the employees file was not created already,
    	 // then create it
    	 if( !fiEmployees->Exists )
    	     StreamWriter ^ stwEmployees = fiEmployees->CreateText();
    	     // And create a John Doe employee
    	    try {
    		 stwEmployees->WriteLine(L"John Doe");
  3. Display the NewEmployee form and double-click its Create button
  4. Implement its Click event as follows:
    System::Void btnCreate_Click(System::Object^  sender, System::EventArgs^  e)
    	 String ^ strFilename = L"C:\\Watts A Loan\\Employees.wal";
    	 FileInfo ^ fiEmployees = gcnew FileInfo(strFilename);
    	 StreamWriter ^ stwEmployees = nullptr;
    	 // Normally, we should have the file already but just in case...
    	 if( !fiEmployees->Exists )
    		 stwEmployees = fiEmployees->CreateText();
    	 else // If the file exists already, then we will only add to it
    		 stwEmployees= fiEmployees->AppendText();
    	 try {
    	 txtEmployeeNumber->Text = L"";
    	 txtEmployeeName->Text = L"";
  5. Return to the (main) form

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.

To check whether a directory exists or not, you can call the Directory::Exists() Boolean static member function. Its syntax is:

    static bool Exists(String ^path);

This member function receives the (complete) path of the directory. If the path exists, the member function returns true. If the directory doesn't exist, the member function returns false.

To create a directory, you can call the CreateDirectory() member function 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() member function, which is overloaded with three versions.

Practical LearningPractical Learning: Using Directories and Files

  1. In the combo box on top of the Properties window, select txtAccountNumber
  2. In the Events section, double-click Leave and implement the event as follows:
    System::Void txtAccountNumber_Leave(System::Object^  sender, System::EventArgs^  e)
        String ^ strPath = L"C:\\Watts A Loan";
        DirectoryInfo ^ diLoans =
             gcnew DirectoryInfo(strPath);
        array<FileInfo ^> ^ aryLoans = diLoans->GetFiles(L"*",
        String ^ strFilename = txtAccountNumber->Text + L".wal";
    	String ^ strFullname = strPath + L"none.wal";
        bool found = false;
        for each(FileInfo ^ fle in aryLoans)
            if( fle->Name == strFilename )
                found = true;
                strFullname = fle->FullName;
        if( found == true )
            FileStream ^ stmLoans =
            BinaryReader ^ bnrLoans = gcnew BinaryReader(stmLoans);
    		txtAccountNumber->Text = bnrLoans->ReadString();
        txtCustomerName->Text = bnrLoans->ReadString();
        txtEmployeeNumber->Text = bnrLoans->ReadString();
        txtEmployeeName->Text = bnrLoans->ReadString();
        txtLoanAmount->Text = bnrLoans->ReadString();
        txtInterestRate->Text = bnrLoans->ReadString();
        txtPeriods->Text = bnrLoans->ReadString();
        txtMonthlyPayment->Text = bnrLoans->ReadString();
  3. In the combo box on top of the Properties window, select txtEmployeeNumber
  4. On the Properties window, click the Events button and double-click Leave
  5. Implement the event as follows:
    System::Void txtEmployeeNumber_Leave(System::Object^  sender, System::EventArgs^  e)
        String ^ strFilename = L"C:\\Watts A Loan\\Employees.wal";
        FileInfo ^ fiEmployees = gcnew FileInfo(strFilename);
        if(fiEmployees->Exists )
    	 if( txtEmployeeNumber->Text == L"" )
                 txtEmployeeName->Text = L"";
    	     StreamReader ^ strEmployees = fiEmployees->OpenText();
    	     String ^ strEmployeeNumber, ^ strEmployeeName;
    	     bool found = false;
    	     try {
    		 while( strEmployeeNumber = strEmployees->ReadLine() )
    	  	     if( strEmployeeNumber == txtEmployeeNumber->Text )
    			 strEmployeeName   = strEmployees->ReadLine();
    			 txtEmployeeName->Text = strEmployeeName;
    			 found = true;
    		  // When the application has finished checking the file
    		  // if there was no employee with that number, let the user know
    		  if( found == false )
    			 MessageBox::Show(L"No employee with that number was found");
    				 txtEmployeeName->Text = L"";
  6. Return to the form and double-click the Save button
  7. Implement the event as follows:
    System::Void btnSave_Click(System::Object^  sender, System::EventArgs^  e)
        String ^ strPath = L"C:\\Watts A Loan\\" + txtAccountNumber->Text + L".wal";
        FileStream ^ stmLoan = File::Create(strPath);
        BinaryWriter ^ bnwLoan =
                    gcnew BinaryWriter(stmLoan);
           txtAccountNumber->Text = L"";
           txtCustomerName->Text = L"";
           txtEmployeeNumber->Text = L"";
           txtEmployeeName->Text = L"";
           txtLoanAmount->Text = L"";
           txtInterestRate->Text = L"";
           txtPeriods->Text = L"";
           txtMonthlyPayment->Text = L"";
  8. Execute the application to test it
  9. First create a few employees as follows:
    Employee # Employee Name
    42-806 Patricia Katts
    75-148 Helene Mukoko
    36-222 Frank Leandro
    42-808 Jennie Lenney
  10. Process a few loans
    Watts A Loan - Loan Preparation
    Watts A Loan - Loan Result
  11. Close the application

Home Copyright © 2010-2016, FunctionX Next