Microsoft Visual C# File Processing: 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:
Practical Learning: Introducing Directories
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 |
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"); } }
private void btnClose_Click(object sender, EventArgs e) { Close(); }
Control | Text | Name |
Label | Employee #: | |
TextBox | txtEmployeeNumber | |
Label | Employee Name: | |
TextBox | txtEmployeeName | |
Button | Create | btnCreate |
Button | Close | btnClose |
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(); } } }
private void btnNewEmployee_Click(object sender, EventArgs e) { NewEmployee frmNewEmployee = new NewEmployee(); frmNewEmployee.ShowDialog(); }
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:
The Directory.CreateDirectory() method returns a DirectoryInfo object that you can use as you see fit.
Practical Learning: Creating a Directory
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(); } } }
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(); }
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.
Practical Learning: Using Directories and Files
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(); } }
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(); } } } }
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(); }
Employee # | Employee Name |
42-806 | Patricia Katts |
75-148 | Helene Mukoko |
36-222 | Frank Leandro |
42-808 | Gertrude Monay |
|
||
Home | Copyright © 2010-2020, FunctionX | |
|