 |
Files Operations |
|
|
|
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
Learning: Introducing Directories
|
|
- Start Microsoft Visual C#
- To create a new application, on the main menu, click File -> New
-> Project...
- In the Templates list, click Windows Application
- Set the name to WattsALoan2 and click OK
- To be able to use the Visual Basic library, in the Solution
Explorer, right-click WattsALoan2 and click Add Reference...
- In the .NET property page, click Microsoft.VisualBasic
- Click OK
- Design the form as follows:
 |
| 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 |
|
- 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");
}
}
|
- 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();
}
|
- Scroll up completely and, under the other using lines, type using System.IO;
- To create a new form, on the main menu, click Project -> Add
Windows Form...
- In the Templates list, make sure Windows Form is selected.
Set the Name to NewEmployee and click Add
- Design the form as follows:
 |
| Control |
Text |
Name |
| Label |
Employee #: |
|
| TextBox |
|
txtEmployeeNumber |
| Label |
Employee Name: |
|
| TextBox |
|
txtEmployeeName |
| Button |
Create |
btnCreate |
| Button |
Close |
btnClose |
|
- Double-click the Close button
- 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();
}
}
}
|
- Access the first form
- 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();
}
|
- Return to the form
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:
- 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 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
- 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.
|
Practical
Learning: Creating a Directory
|
|
- On the (main) form, double-click an unoccupied area of its body
- 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();
}
}
}
|
- Display the NewEmployee form and double-click its Create button
- 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();
}
|
- 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.
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.
|
Practical
Learning: Using Directories and Files
|
|
- In the combo box on top of the Properties window, select
txtAccountNumber
- 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();
}
}
|
- In the combo box on top of the Properties window, select
txtEmployeeNumber
- On the Properties window, click the Events button and double-click
Leave
- 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();
}
}
}
}
|
- Return to the form and double-click the Save button
- 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();
}
|
- Execute the application to test it
- 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 |
- Process a few loans
- Close the application
|
Routine Operations on Files |
|
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. Their syntaxes are:
public FileStream Open(FileMode mode);
public FileStream Open(FileMode mode,
FileAccess access);
public FileStream Open(FileMode mode,
FileAccess access,
FileShare share);
You can select one of these methods, depending on how
you want to open the file, using the options for file
mode, file access, and file
sharing. Each version of this method returns a FileStream
object that you can then use to process the file. After opening the file,
you can then read or use its content.
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:
FileInfo fleMembers = new FileInfo("First.txt");
fleMembers.Delete();
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. One of the versions 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:
FileInfo fleMembers = new FileInfo("Reality.txt");
string strMyDocuments =
Environment.GetFolderPath(Environment.SpecialFolder.Personal);
fleMembers.CopyTo(string.Concat(strMyDocuments, "\\Federal.txt"));
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 second argument as true; otherwise, pass it as false.
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 a 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:
FileInfo fleMembers = new FileInfo("pop.txt");
string strMyDocuments = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
fleMembers.CopyTo(string.Concat(strMyDocuments, "\\pop.txt"));
|
Characteristics of a File |
|
|
The Date and Time a File Was Created |
|
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 get accessor of the FileSystemInfo.CreationTime
property, which is of type DateTime. Here is an example of using it:
DateTime dteCreationTime = fleLoan.CreationTime;
label1.Text = "Date and Time Created: " + dteCreationTime.ToString();
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 set accessor of the FileSystemInfo.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, which
is of type DateTime.
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, which is of type DateTime.
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:
MessageBox.Show("The name of this file is: \"" + fleLoan.Name + "\"");
This string simply identifies 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:
MessageBox.Show("File Extension: " + fleLoan.Extension);
One of the routine operations the operating system
performs consists of calculating the size 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:
MessageBox.Show("File Size: " + fleLoan.Length.ToString());
Besides its name, a file 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.
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 create 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.
- Open the WattsALoan2 application from this lesson
- Provide tool tips for the various controls
- Provide help to the application
|
|