Home

Drives and their Contents

 

Introduction to Drives

 

Introduction

A drive is a physical device attached to a computer so it can store information. A drive can be a hard disk, a CD ROM, a DVD ROM, a flash (USB) drive, a memory card etc:

Hard Drive DVD Drive USB Flash Drive
Hard Drive DVD Drive USB Flash Drive
      
Floppy Drive Memory Card
Floppy Drive Flash Memory

A drive can reside inside a computer. That's the case for internal hard drives and most CD or DVD drives. A drive can also reside outside. That's the case for most flash (USB) drives. There are also versions of external hard drives and external DVD drives:

Hard Drive Floppy Drive USB Flash Drive
External Hard Drive External Floppy Drive USB Flash Drive Holder

A drive is referred to as virtual if it is not a real physical object. For example, a hard drive can be divided or partitioned internally, giving birth to each part that acts as its own drive.

While most drives are connected to a computer, a device connected to another computer can also be used as a drive. In this case, while the drive is connected to a computer A, a computer B must be connected to the computer A in order to use the drive on computer A. This is the case in computer networks where drives (or their contents) are shared.

Not all computers have the same drives and not all computers deal with the same means of storing data. Still, to simplify their identification, all objects used to hold data are referred to as drives. Because there are different ways to consider drives, there are also various means of accessing them.

There are two techniques of referring to drives. A drive that is directly connected to a computer, whether internally or externally, is referred to as a local drive. In Microsoft Windows, a local drive is represented by a letter, in uppercase, followed by a colon ":", and a backslash "\". Traditionally, drive A:\ is used for a 3.5" floppy drive that uses 3.5" floppy disks. Most computers nowadays don't (or hardly) use floppy disks. That drive is almost never used but, because of legacy, it is still represented in the Microsoft Windows operating system. Also, traditionally, drive B:\ was used for a 5.25" floppy drive that used 5.25" floppy disks. These disks have almost disappeared completely. Based on operating system legacy, in some computers, drive B:\ is still represented in computers (many computers don't show any drive B:\ anymore). Drive C:\ usually represents the main hard drive of a computer. The other letters assigned to the other drive are not standard; they vary from one computer to another. If a hard disk is partitioned, each partition uses its own letter and is represented as its own drive.

Getting the List of Drives of a Computer

Normally, you will hardly be concerned with the creation of drives. The operating system "creates" or assigns a drive whenever it juges it necessary. For example, as soon as you connect a USB drive to a port, the operating system automatically creates a drive and assigns a lette to it. You will only need to identify the drives that are available on a computer on which  your application is running. One of the primary operations you will perform consists of getting a list of drives on the computer.

The .NET Framework provides many classes that can assist you to identify the drives of a computer. To start, the Environment class is equipped with a method named GetLogicalDrives. Its syntax is:

public static string[] GetLogicalDrives()

When called, this method produces an array of string where each element represents a logical in the computer. You can then use the drives as you see fit. Here is an example:

private void btnDrives_Click(object sender, EventArgs e)
{
    string[] strDrives = Environment.GetLogicalDrives();

    foreach (string strDrive in strDrives)
        MessageBox.Show("Logical Drive: " + strDrive,
                        "Logical Drives",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
}

Besides the Environment.GetLogicalDrives() method, the DriveInfo class provides its own means of getting a list of logical drives on the local computer. This is done through the GetDrives(). Its syntax is:

public static DriveInfo[] GetDrives();

As opposed to a list of strings, the DriveInfo.GetDrives() method produces an array of DriveInfo objects, which is an array of logical drives on the computer. Here is an example of calling this method:

private void btnDrives_Click(object sender, EventArgs e)
{
    DriveInfo[] diLocalDrives = DriveInfo.GetDrives();
}

Characteristics of Drives

 

Introduction

In microsoft Windows, a local drive is represented by a letter followed by :\. For example, in most personal computers, the (main) hard drive is represented as C:\.

The main class used to manage the drives of a computer is named DriveInfo. If you know the drive you want to use or access, the DriveInfo class provides a constructor that allows you to get a reference to that drive. This is the only constructor of this class. The syntax of the constructor is:

public DriveInfo(string driveName);

If you want to access a drive, you can declare a DriveInfo variable and pass the drive letter to this constructor. Here is an example:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Drives1
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnDrives_Click(object sender, EventArgs e)
        {
            DriveInfo diHardDrive = new DriveInfo(@"C:\");
        }
    }
}

The Name of a Drive

If you want to get the name of a drive, you can access the Name property of the DriveInfo class:

public string Name { get; }

Here is an example:

private void btnDrives_Click(object sender, EventArgs e)
{
    DriveInfo[] diLocalDrives = DriveInfo.GetDrives();

    foreach (DriveInfo diLogicalDrive in diLocalDrives)
        MessageBox.Show("Logical Drive: " + diLogicalDrive.Name,
                        "Logical Drives",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
}

The Type of a Drive

A drive is primarily recognized by its category. Examples of categories are hard drives, CD and DVD drives, etc. The categories of drives are stored in the DriveType property of the DriveInfo class. The DriveType property is based on an enumeration of the same name:

public DriveType DriveType { get; }

Its members are:

Member Description
Unknown The drive is unrecognizable
NoRootDirectory The root of the drive is unrecognizable
Removable This can be a floppy drive, a USB drive, a memory card, etc. A drive that can be removed at will
Fixed This is a hard drive or a partition on an HD
Network This is a network drive, usually located on another computer
CDROM This is drive CD or DVD drive
Ram This is the random access memory

The Type of Format

The format system is the scheme that a computer (actually the operating system) uses to store and process the values in its drives. Microsoft Windows uses various types of formats, including FAT32 and NTFS. To know the format scheme that a drive is using, get the value of the DriveFormat property of the DriveInfo class:

public string DriveFormat { get; }

Here is an example of accessing this property:

private void btnDrives_Click(object sender, EventArgs e)
{
    DriveInfo diHardDrive = new DriveInfo(@"C:\");

    if( diHardDrive != null  )
        MessageBox.Show("Operating System:  " + 
                        Environment.OSVersion.ToString() + Environment.NewLine +
                        "Drive Format:      " + diHardDrive.DriveFormat,
                        "Exercise",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
}

The Capacity of a Drive

A drive is priarily used to hold some values. The capacity of a drive is the amount of data it can hold. This is usually measured in bits and bytes. As there are various types of drives, they also have different capacities. To help you to know the capacity of a drive, the DriveInfo class is equipped with a property named TotalSize:

public long TotalSize { get; }

This property produces a long integer that represents the normal total capacity of a drive. Here is an example of accessing it:

private void btnDrives_Click(object sender, EventArgs e)
{
    DriveInfo diHardDrive = new DriveInfo(@"C:\");

    if( diHardDrive != null  )
        MessageBox.Show("You hard drive has a capacity of " +
                        diHardDrive.TotalSize.ToString() + " bytes.",
                        "Logical Drives",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
}

As values are stored in a drive, it gets filled up. In some drives, values can be deleted, copied, or moved. This means that the capacity of some drives changes some time to time. At one time, to know the available free space of a drive, you can get the value of the AvailableFreeSpace property of its DriveInfo object:

public long AvailableFreeSpace { get; }

Here is an example of accessing this property:

private void btnDrives_Click(object sender, EventArgs e)
{
    DriveInfo diHardDrive = new DriveInfo(@"C:\");

    if( diHardDrive != null  )
        MessageBox.Show("Hard Drive Capacity:  " +
                        diHardDrive.TotalSize.ToString() + " bytes.\n" +
                        "Available Free Space: " +
                        diHardDrive.AvailableFreeSpace.ToString() + " bytes.\n",
                        "Exercise",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
}

Directories

 

Introduction

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:

The similarities of both types are:

ApplicationApplication: Introducing Directories

  1. Start Microsoft Visual C#
  2. To create a new application, on the main menu, click File -> New -> Project...
  3. In the middle list, click Windows Application
  4. Set the name to WattsALoan2 and click OK
  5. To be able to use the Visual Basic library, in the Solution Explorer, right-click WattsALoan2 and click Add Reference...
  6. In the .NET property page, click Microsoft.VisualBasic
     
    Add Reference
  7. Click OK
  8. Design the form as follows:
     
    Watts' A Loan
    Control Name Text
    Label   If this is a new loan, enter a new account number and the name of the customer who is requesting the loan
    Label   To open a previously prepared loan, enter its account number and press Tab
    Label   Acnt #:
    Label   Customer Name:
    Label   Customer:
    TextBox txtAccountNumber  
    TextBox txtCustomerName  
    Label   Empl #:
    Label   Employee Name:
    Label   Prepared By:
    TextBox txtEmployeeNumber  
    TextBox txtEmployeeName  
    Button btnNewEmployee  
    Button btnNewCustomer  
    Label   Loan Amount:
    TextBox txtLoanAmount  
    Label   Interest Rate:
    TextBox txtInterestRate  
    Label   %
    Label   Periods
    TextBox   txtPeriods
    Button btnCalculate Calculate
    Label   Monthly Payment:
    TextBox txtMonthlyPayment  
    Button btnClose Close
  9. Double-click the Calculate button and implement its event as follows:
    private void btnCalculate_Click(object sender, EventArgs e)
    {
        double LoanAmount     = 0.00,
               InterestRate   = 0.00,
               Periods        = 0.00,
               MonthlyPayment = 0.00;
    
        try {
    	 LoanAmount = double.Parse(txtLoanAmount.Text);
        }
        catch(FormatException)
        {
    	 MessageBox.Show("Invalid Loan Amount");
        }
    				 
        try {
    	 InterestRate = double.Parse(txtInterestRate.Text);
        }
        catch(FormatException)
        {
    	 MessageBox.Show("Invalid Interest Rate");
        }
    				 
        try {
    	 Periods = double.Parse(txtPeriods.Text);
        }
        catch(FormatException)
        {
    	 MessageBox.Show("Invalid Periods Value");
        }
    				 
        try {
    	 MonthlyPayment =
    	     Microsoft.VisualBasic.Financial.Pmt(
    			InterestRate/ 12 / 100,
    		        Periods,
    			-LoanAmount,
    			0 ,
    			Microsoft.VisualBasic.DueDate.BegOfPeriod);
    	 txtMonthlyPayment.Text = MonthlyPayment.ToString("F");
        }
        catch(FormatException)
        {
    	 MessageBox.Show("Invalid Periods Value");
        }
    }
  10. Return to the form and double-click the Close button to implement its event as follows:
    private void btnClose_Click(object sender, EventArgs e)
    {
        Close();
    }
  11. Scroll up completely and, under the other using lines, type using System.IO;
  12. To create a new form, on the main menu, click Project -> Add Windows Form...
  13. In the middle list, make sure Windows Form is selected.
    Set the Name to NewEmployee and click Add
  14. Design the form as follows:
     
    Control Text Name
    Label Employee #:
    TextBox txtEmployeeNumber
    Label Employee Name:
    TextBox txtEmployeeName
    Button Create btnCreate
    Button Close btnClose
  15. Double-click the Close button
  16. Implement the event as follows:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    
    namespace WattsALoan2
    {
        public partial class NewEmployee : Form
        {
            public NewEmployee()
            {
                InitializeComponent();
            }
    
            private void btnClose_Click(object sender, EventArgs e)
            {
                Close();
            }
        }
    }
  17. Access the first form
  18. Double-click the New button and implement the event as follows:
    private void btnNewEmployee_Click(object sender, EventArgs e)
    {
        NewEmployee frmNewEmployee = new NewEmployee();
    
        frmNewEmployee.ShowDialog();
    }
  19. 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 called Directory. Directory is a static class. 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 directory 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 d until the end of the specified path

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

ApplicationApplication: Creating a Directory

  1. On the (main) form, double-click an unoccupied area of its body
  2. Implement its Load event as follows:
    private void Form1_Load(object sender, EventArgs e)
    {
        string strDirectory = "C:\\Watts A Loan";
    
        if (!Directory.Exists(strDirectory))
            Directory.CreateDirectory(strDirectory);
    
        string strFilename = strDirectory + "\\Employees.wal";
    
        FileInfo fiEmployees = new 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("00-000");
                stwEmployees.WriteLine("John Doe");
            }
            finally
            {
                stwEmployees.Close();
            }
        }
    }
  3. Display the NewEmployee form and double-click its Create button
  4. Implement its Click event as follows:
    private void btnCreate_Click(object sender, EventArgs e)
    {
        string strFilename = "C:\\Watts A Loan\\Employees.wal";
        FileInfo fiEmployees = new FileInfo(strFilename);
        StreamWriter stwEmployees = null;
    
        // 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
        {
            stwEmployees.WriteLine(txtEmployeeNumber.Text);
            stwEmployees.WriteLine(txtEmployeeName.Text);
        }
        finally
        {
            stwEmployees.Close();
        }
    
        txtEmployeeNumber.Text = "";
        txtEmployeeName.Text = "";
        txtEmployeeNumber.Focus();
    }
  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 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.

Deleting a Directory

To get rid of a directory, you can call the Delete() method of the Directory class. It is overloaded with two versions. One of the versions uses the following syntax;

public static void Delete(string path);

When calling this method, pass the complete path as argument. The other version uses the following syntax:

public static void Delete(string path, bool recursive);

This time, the second argument allows you to specifies whether you want the sub-folders and their contents to be deleted also.

Listing the Files of a Directory

One of the most routine operations performed in a directory consists of looking for a file. 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. 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:
    private void txtAccountNumber_Leave(object sender, EventArgs e)
    {
        string strPath = "C:\\Watts A Loan";
    
        DirectoryInfo diLoans =
             new DirectoryInfo(strPath);
        FileInfo[] aryLoans = diLoans.GetFiles("*",
    		SearchOption.AllDirectories);
    
        string strFilename = txtAccountNumber.Text + ".wal";
        string strFullname = strPath + "none.wal";
        bool found = false;
    
        foreach(FileInfo fle in aryLoans)
        {
            if( fle.Name == strFilename )
            {
                found = true;
                strFullname = fle.FullName;
            }
        }
    
        if( found == true )
        {
            FileStream stmLoans = File.Open(strFullname,
                                  FileMode.Open,
                                  FileAccess.Read);
            BinaryReader bnrLoans = new 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();
    
            bnrLoans.Close();
            stmLoans.Close();
        }
    }
  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:
    private void txtEmployeeNumber_Leave(object sender, EventArgs e)
    {
        string strFilename = "C:\\Watts A Loan\\Employees.wal";
        FileInfo fiEmployees = new FileInfo(strFilename);
    
        if (fiEmployees.Exists)
        {
            if (txtEmployeeNumber.Text == "")
            {
                txtEmployeeName.Text = "";
                return;
            }
            else
            {
                StreamReader strEmployees = fiEmployees.OpenText();
                string strEmployeeNumber, strEmployeeName;
                bool found = false;
    
                try
                {
                    using (strEmployees = new StreamReader(strFilename))
                    {
                        while (strEmployees.Peek() >= 0)
                        {
                            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("No employee with that number was found");
                        txtEmployeeName.Text = "";
                        txtEmployeeNumber.Focus();
                    }
                }
                finally
                {
                    strEmployees.Close();
                }
            }
        }
    }
  6. Return to the form and double-click the Save button
  7. Implement the event as follows:
    private void btnSave_Click(object sender, EventArgs e)
    {
        string strPath = "C:\\Watts A Loan\\" + txtAccountNumber.Text + ".wal";
    
        FileStream stmLoan = File.Create(strPath);
        BinaryWriter bnwLoan = new BinaryWriter(stmLoan);
    
        bnwLoan.Write(txtAccountNumber.Text);
        bnwLoan.Write(txtCustomerName.Text);
        bnwLoan.Write(txtEmployeeNumber.Text);
        bnwLoan.Write(txtEmployeeName.Text);
        bnwLoan.Write(txtLoanAmount.Text);
        bnwLoan.Write(txtInterestRate.Text);
        bnwLoan.Write(txtPeriods.Text);
        bnwLoan.Write(txtMonthlyPayment.Text);
    
        txtAccountNumber.Text = "";
        txtCustomerName.Text = "";
        txtEmployeeNumber.Text = "";
        txtEmployeeName.Text = "";
        txtLoanAmount.Text = "";
        txtInterestRate.Text = "";
        txtPeriods.Text = "";
        txtMonthlyPayment.Text = "";
    
        txtAccountNumber.Focus();
    
        bnwLoan.Close();
        stmLoan.Close();
    }
  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 Gertrude Monay
  10. Process a few loans
     
    Watts A Loan - Loan Preparation
     
    Watts A Loan - Loan Result
  11. Close the application

Exercises

 

Watts A Loan

  1. Open the WattsALoan1 application from this lesson
  2. Provide tool tips for the various controls
  3. Provide help to the application

Clarksville Ice Cream

  1. Open the ClarskvilleIceCream application from the previous lesson
  2. In the sections that deal with file processing add a finally block
  3. Write your code to handle the FileNotFoundException exception

Previous Copyright © 2005-2010 FunctionX Next