Home

Operations on Files

 

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.

 

Practical Learning Practical Learning: Opening a File

  1. To allow the user to open a file, change the source file in Notepad as follows:
     
    using System;
    using System.IO;
    using System.Collections;
    
    namespace CarLoan
    {
        sealed public class CEmployee
        {
    	public string EmployeeNumber;
    	public string FullName;
        }
    
        public class Exercise
        {
    	private static void CreateNewEmployee()
    	{
    	    string employeeNumber, employeeName;
    	    FileInfo fleEmployees = new FileInfo("Employees.txt");
    	    StreamWriter swrEmployees = null;
    	    
    	    // If the file exists already, then add the new employee to it
    	    if( fleEmployees.Exists == true )
    		swrEmployees = fleEmployees.AppendText();
    	    else // Otherwise, create a new file
    		swrEmployees = fleEmployees.CreateText();
    
    	    try 
    	    {
    		Console.WriteLine("Hiring New Employee");
    		Console.Write("Enter Employee Number as 00-000: ");
    		employeeNumber = Console.ReadLine();
    		Console.Write("Enter Employee Name: ");
    		employeeName = Console.ReadLine();
    
    		swrEmployees.WriteLine(employeeNumber);
    		swrEmployees.WriteLine(employeeName);
    
    	    }
    	    finally
    	    {
    		swrEmployees.Flush();
    		swrEmployees.Close();
    	    }
    	}
    
    	private static string GetEmployeeName(string EmplNbr)
    	{
    	    // 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 argument
    		 // then return it
    		 if( empl.EmployeeNumber == EmplNbr )
    			 return empl.FullName;
    	    }
    
    	    // If the employee number was not found, then return null
    	    return "00-000";
    	}
    
    	static void PrepareNewLoan()
    	{
    	    int answer = 0;
    
    	    do {
    		Console.Write("Do you want to hire a new employee(0=No/1=Yes)? ");
    		answer = int.Parse(Console.ReadLine());
    
    		if( answer == 1 )
    		    CreateNewEmployee();
    	    } while(answer == 1);
    
    	    string employeeNumber = "00-000", employeeName = "Not Specified";
    	    string applicantName, employerName;
    	    string homePhone, workPhone;
    	    double loanAmount, interestRate, monthlyPayment, periods;
    
    	    Console.WriteLine("Enter the following pieces of information\n");
    
    Console.Write("Enter the employee number of the clerk preparing the loan (00-000): ");
    	    employeeNumber = Console.ReadLine();
    	    employeeName = GetEmployeeName(employeeNumber);
    
    	    Console.WriteLine("Enter the Applicant's Information");
    	    Console.Write("Full Name:     ");
    	    applicantName = Console.ReadLine();
    	    Console.Write("Employer Name: ");
    	    employerName = Console.ReadLine();
    	    Console.Write("Home Phone:    ");
    	    homePhone = Console.ReadLine();
    	    Console.Write("Work Phone:    ");
    	    workPhone = Console.ReadLine();
    	    Console.WriteLine("Loan Estimation");
    	    Console.Write("Amount of Loan: ");
     	    loanAmount   = double.Parse(Console.ReadLine());
    	    Console.Write("Interest Rate(0 to 100): ");
    	    interestRate = double.Parse(Console.ReadLine()) / 100;
    	    Console.Write("Number of Months: ");
    	    periods = double.Parse(Console.ReadLine());
    
    	    monthlyPayment = Microsoft.VisualBasic.Financial.Pmt(
    			interestRate/12, periods, -loanAmount, 0, 
    			Microsoft.VisualBasic.DueDate.BegOfPeriod);
    
    	    Console.WriteLine("");
    	    Console.WriteLine(" -=-=-=-=-=-=-=-=-=-=-=-=-=-=");
    	    Console.WriteLine(" -=- Car Loan Application -=-");
    	    Console.WriteLine(" -=-=-=-=-=-=-=-=-=-=-=-=-=-=");
    	    Console.WriteLine("Prepared By: {0} {1}", employeeNumber, employeeName);
    	    Console.WriteLine("Applicant Information");
    	    Console.WriteLine("Full Name:        {0}", applicantName);
    	    Console.WriteLine("Employer Name:    {0}", employerName);
    	    Console.WriteLine("Home Phone:       {0}", homePhone);
    	    Console.WriteLine("Work Phone:       {0}", workPhone);
    	    Console.WriteLine("Loan Estimation");
    	    Console.WriteLine("Loan Amount:      {0:C}", loanAmount);
    	    Console.WriteLine("Interest Rate:    {0:P}", interestRate);
    	    Console.WriteLine("Number of Months: {0}", periods);
    	    Console.WriteLine("Monthly Payment:  {0:C}", monthlyPayment);
    
    	    Console.Write("Do you want to save this preparation (0=No/1=Yes): ");
    	    int saveAnwer = int.Parse(Console.ReadLine());
    	    
    	    if( saveAnwer == 1 )
    	    {
    
    	Console.Write("Enter the name to save the file as (don't add an extension): ");
    		string fileName = Console.ReadLine();
    	
    		FileInfo fleLoan = new FileInfo(fileName + ".txt");
    		StreamWriter swrLoan = fleLoan.CreateText();
    
    		try 
    		{
    		    swrLoan.WriteLine(employeeNumber);
    		    swrLoan.WriteLine(employeeName);
    		    swrLoan.WriteLine(applicantName);
    		    swrLoan.WriteLine(employerName);
    		    swrLoan.WriteLine(homePhone);
    		    swrLoan.WriteLine(workPhone);
    		    swrLoan.WriteLine(loanAmount);
    		    swrLoan.WriteLine(interestRate);
    		    swrLoan.WriteLine(periods);
    		    swrLoan.WriteLine(monthlyPayment);
    		}
    		finally
    		{
    			swrLoan.Flush();
    			swrLoan.Close();
    		}
    	    }
    	}
    
    	static void OpenExistingLoan()
    	{
    Console.Write("Enter the name of the file to open (don't specify the extension): ");
    	    string fileName = Console.ReadLine();
    
    	    // Create a FileInfo object based on the file
    	    FileInfo fleLoan = new FileInfo(fileName + ".txt");
    	    // Open the file
    	    StreamReader stmLoan = fleLoan.OpenText();
    
    	    // Use exception handling just in case
    	    try 
    	    {
    		Console.WriteLine("");
    		Console.WriteLine(" -=-=-=-=-=-=-=-=-=-=-=-=-=-=");
    		Console.WriteLine(" -=- Car Loan Application -=-");
    		Console.WriteLine(" -=-=-=-=-=-=-=-=-=-=-=-=-=-=");
    Console.WriteLine("Prepared By: {0} {1}", stmLoan.ReadLine(), stmLoan.ReadLine());
    		Console.WriteLine("Applicant Information");
    		Console.WriteLine("Full Name:        {0}", stmLoan.ReadLine());
    		Console.WriteLine("Employer Name:    {0}", stmLoan.ReadLine());
    		Console.WriteLine("Home Phone:       {0}", stmLoan.ReadLine());
    		Console.WriteLine("Work Phone:       {0}", stmLoan.ReadLine());
    		Console.WriteLine("Loan Estimation");
    Console.WriteLine("Loan Amount:      {0:C}", double.Parse(stmLoan.ReadLine()));
    Console.WriteLine("Interest Rate:    {0:P}", double.Parse(stmLoan.ReadLine()));
    	Console.WriteLine("Number of Months: {0}", int.Parse(stmLoan.ReadLine()));
    Console.WriteLine("Monthly Payment:  {0:C}", double.Parse(stmLoan.ReadLine()));
    	    }
    	    finally
    	    {
    		stmLoan.Close();
    	    }
    	}
    
    	static int Main()
    	{
    	    int menuAnswer = 0;
    
    	    Console.WriteLine(" -=- Car Loan Application -=-");
    
    	    Console.WriteLine("Main Menu");
    	    Console.WriteLine("1. Prepare a new loan");
    	    Console.WriteLine("2. Open a recently prepared loan");
    	    Console.WriteLine("3. Exit");
    	    menuAnswer = int.Parse(Console.ReadLine());
    
    	    switch(menuAnswer)
    	    {
    	    case 1:
    		PrepareNewLoan();
    		break;
    	    case 2:
    		OpenExistingLoan();
    		break;
    	    }
    
    	    return 0;
    	}
        }
    }
  2. Save the file and return to the Command Prompt
  3. To compile the exercise, type:
     
    csc /out:"Car Loan".exe /reference:Microsoft.VisualBasic.dll exercise.cs
  4. Press Enter
  5. Perform various operations and return to Notepad
 

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:

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:

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:

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 

To keep track of it, 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 FileSystemInfo.get_CreationTime() property is. This would be done as follows:

DateTime dteCreationTime = fleLoan.CreationTime;
MessageBox.Show("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 FileSystemInfo.set_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.

If you are interested in know the last date and time a file was modified, you can get the value of its FileSystemInfo.LastWriteTime property. You can also change this value if you want to make sure the file holds your own.

 

The Name of a File

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.

 

The Extension of 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 confusions that this can lead to, most applications assist the user with this detail. For example, when we implemented the routines that allow the user to save or open a file, we specified a default extension for the Save Dialog or the Open Dialog objects. This allows the user not to care for the extension. Based on this, 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);
 

The Size of a File

One of the routine operations the operating system performs consists of calculation 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());

 

 

The Path to a File

Besides the name of the file, it 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.

 

The Attributes of a File

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 accessed or open a file, to get its attributes, you can access the value of its FileSystemInfo.get_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 a FileAttributes object and assign it to the FileSystemInfo.set_Attributes() property.

FileAttributes is an enumerator with the following members: Archive, Compressed, Device, Directory, Encrypted, Hidden, Normal, NotContentIndexed, Offline, ReadOnly, ReparsePoint, SparseFile, System, and Temporary.

 
 

Previous Copyright © 2005-2016, FunctionX