Home

File Information: Operations on Files

 

Opening a File

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.

If you have a text-based file and want to directly read from it, you can use the StreamReader class that is equipped with Read() and ReadLine() methods. As done for the StreamWriter class, after using a StreamReader object, make sure you close it.

Here is an example:

private void btnOpen_Click(object sender, System.EventArgs e)
{
	StreamReader rdrMembers = new StreamReader("First.txt");
	txtFirstName.Text       = rdrMembers.ReadLine();
	txtLastName.Text       = rdrMembers.ReadLine();
	txtHomePhone.Text    = rdrMembers.ReadLine();
	txtEmailAddress.Text  = rdrMembers.ReadLine();
	rdrMembers.Close();
}
 

Practical Learning Practical Learning: Opening a File

  1. Display the first form of the project and click the text box on the right side of the Prepared By label
  2. In the Properties window, click the Events button and double-click Leave
  3. In the top section of the file, create a sealed managed class named CEmployee as follows:
     
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    using System.IO;
    
    sealed public class CEmployee
    {
    	public string EmployeeNumber;
    	public string FullName;
    }
    
    namespace CarLoans1
  4. Implement the new event as follows:
     
    private void txtEmployeeNumber_Leave(object sender, System.EventArgs e)
    {
    	// Create a FileInfo object based on the file that contains the employees
    	 FileInfo fleEmployees = new FileInfo("Employees.txt");
    	 // Open the file
    	 StreamReader stmEmployees = fleEmployees.OpenText();
    	 // We will need to create a list of employees from the file
    	 ArrayList lstEmployees = new ArrayList();
    
    	 // Use exception handling just in case
    	 try {
    		 // This String variable will hold a line of text
    		 String strData = null;
    
    		 // "Scan" the file, reading each line
    		 while( (strData = stmEmployees.ReadLine()) != null )
    		 {
    			 // We will need to locate each employee
    			 CEmployee empl = new CEmployee();
    		// Get the current line of text as the employee number
    	 // and store its value in the first member of the local class
    			 empl.EmployeeNumber = strData;
    			 // Store the next line of text as employee name
    		 // in the second member variable of the CEmployee object
    			 empl.FullName = stmEmployees.ReadLine();
    	 // Now, store the CEmployee object as an item of the list
    			 lstEmployees.Add(empl);
    		 }
    	 }
    	 finally
    	 {
    		 stmEmployees.Close();
    	 }
    
    	 // After creating a list of employees based on the file,
    	 // "scan" the list to locate each employee
    	 for(int i = 0; i < lstEmployees.Count; i++)
    	 {
    		 // Retrieve each CEmployee object
    		 CEmployee empl = (CEmployee)lstEmployees[i];
    	 // If you find an employee number that corresponds to the value
    	 // in the Prepared By text box, retrieve its corresponding
    	 // employee name and display it in the next text box
    		 if( empl.EmployeeNumber.Equals(txtEmployeeNumber.Text) )
    			 txtEmployeeName.Text = empl.FullName;
    	 }
    }
  5. Display the first form.
    In the Toolbox, click the SaveFileDialog button and click the form
  6. In the Properties window, change its characteristics as follows:
    DefaultExt: txt
    Filter: Loan Preparation (*.txt)|*.txt|All Files(*.*)|
    Title: Save Loan Preparation As
  7. In the Toolbox, click the OpenFileDialog button and click the form
  8. In the Properties window, change its characteristics as follows:
    DefaultExt: txt
    Filter: Loan Preparation (*.txt)|*.txt|All Files(*.*)|
    Title: Open Existing Loan Preparation
  9. Save all
  10. On the form, click File and double-click the Save menu item
  11. Implement the event as follows:
     
    private void mnuFileSave_Click(object sender, System.EventArgs e)
    {
    	if( txtEmployeeNumber.Text.Equals("") ||
    		txtEmployeeNumber.Text.Equals("00-000") )
    	{
    	MessageBox.Show("You must enter the employee number of the clerk " +
    				"who prepared the loan");
    		txtEmployeeNumber.Text = "00-000";
    		txtEmployeeNumber.Focus();
    		return;
    	}
    
    	if( txtFullName.Text.Equals("") )
    	{
    	MessageBox.Show("You must enter the name of the customer whose loan " +
    				"was prepared");
    		txtFullName.Focus();
    		return;
    	}
    
    	if( txtLoanAmount.Text.Equals("") || txtLoanAmount.Text.Equals("0.00") )
    	{
    		MessageBox.Show("Invalid Loan Amount");
    		txtLoanAmount.Focus();
    		return;
    	}
    
    	if( txtInterestRate.Text.Equals("") )
    	{
    		MessageBox.Show("Invalid Interest Rate");
    		txtInterestRate.Focus();
    		return;
    	}
    
    	if( txtPeriods.Text.Equals("") )
    	{
    		MessageBox.Show("Invalid number of period");
    		txtPeriods.Focus();
    		return;
    	}
    
    	CalculateLoan();
    
    	if( saveFileDialog1.ShowDialog() == DialogResult.OK )
    	{
    		FileInfo fleLoan = new FileInfo(saveFileDialog1.FileName);
    		StreamWriter swrLoan = fleLoan.CreateText();
    
    		try 
    		{
    			swrLoan.WriteLine(txtEmployeeNumber.Text);
    			swrLoan.WriteLine(txtEmployeeName.Text);
    			swrLoan.WriteLine(txtFullName.Text);
    			swrLoan.WriteLine(txtEmployerName.Text);
    			swrLoan.WriteLine(txtHomePhone.Text);
    			swrLoan.WriteLine(txtWorkPhone.Text);
    			swrLoan.WriteLine(txtLoanAmount.Text);
    			swrLoan.WriteLine(txtInterestRate.Text);
    			swrLoan.WriteLine(txtPeriods.Text);
    			swrLoan.WriteLine(txtPayment.Text);
    
    			txtEmployeeNumber.Text = "00-000";
    			txtEmployeeName.Text   = "";
    			txtFullName.Text = "";
    			txtEmployerName.Text = "";
    			txtHomePhone.Text = "";
    			txtWorkPhone.Text = "";
    			txtLoanAmount.Text = "0.00";
    			txtInterestRate.Text = "8.25";
    			txtPeriods.Text = "60";
    			txtPayment.Text = "0.00";
     
    			txtEmployeeNumber.Focus();
    		}
    		finally
    		{
    			swrLoan.Flush();
    			swrLoan.Close();
    		}
    	}
    }
  12. Return to the form, click File and double-click the Open menu item
  13. Implement the event as follows:
     
    private void mnuFileOpen_Click(object sender, System.EventArgs e)
    {
    	if( openFileDialog1.ShowDialog() == DialogResult.OK )
    	{
    		// Create a FileInfo object based on the file
    		FileInfo fleLoan = new FileInfo(openFileDialog1.FileName);
    		// Open the file
    		StreamReader stmLoan = fleLoan.OpenText();
    
    		// Use exception handling just in case
    		try 
    		{
    			txtEmployeeNumber.Text = stmLoan.ReadLine();
    			txtEmployeeName.Text = stmLoan.ReadLine();
    			txtFullName.Text = stmLoan.ReadLine();
    			txtEmployerName.Text = stmLoan.ReadLine();
    			txtHomePhone.Text = stmLoan.ReadLine();
    			txtWorkPhone.Text = stmLoan.ReadLine();
    			txtLoanAmount.Text = stmLoan.ReadLine();
    			txtInterestRate.Text = stmLoan.ReadLine();
    			txtPeriods.Text = stmLoan.ReadLine();
    			txtPayment.Text = stmLoan.ReadLine();
    		}
    		finally
    		{
    			stmLoan.Close();
    		}
    	}
    }
  14. Execute the application
 

Deleting a File

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 void Delete();

Here is an example:

private void btnDelete_Click(object sender, System.EventArgs e)
{
	FileInfo fleMembers = new FileInfo("First.txt");
	fleMembers.Delete();
}
 

Copying a File

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. The first version 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:

private void btnCopy_Click(object sender, System.EventArgs e)
{
	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 local computer.

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 argument as true; otherwise, pass it as false.

 

Moving a File

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 the 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:

private void btnMove_Click(object sender, System.EventArgs e)
{
	FileInfo fleMembers = new FileInfo("pop.txt");
	String strMyDocuments = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
	fleMembers.CopyTo(String.Concat(strMyDocuments, "\\pop.txt"));
}
 
 

Previous Copyright © 2005-2016, FunctionX Next