Home

File Information

 

File Information Fundamentals

 

Introduction

In its high level of support for file processing, the .NET Framework provides the FileInfo class. This class is equipped to handle all types of file-related operations including creating, copying, moving, renaming, or deleting a file. FileInfo is based on the FileSystemInfo class that provides information on characteristics of a file.

 

Practical Learning Practical Learning: Introducing File Information

  1. Start Notepad and, in the empty file, type the following:
     
    using System;
    using System.IO;
    
    class Program
    {
        static int Main()
        {
            string EmployerName, ApplicantName;
            string HomePhone, WorkPhone;
            double LoanAmount, InterestRate;
            double MonthlyPayment, Periods;
    
            Console.WriteLine(" -=- Car Loan Application -=-");
            Console.WriteLine("Enter the following pieces of information\n");
            Console.WriteLine("Applicant 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(" -=- Car Loan Application -=-");
            Console.WriteLine(" -=-=-=-=-=-=-=-=-=-=-=-=-=-=");
            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:F}", Periods);
            Console.WriteLine("Monthly Payment:  {0:C}", MonthlyPayment);
        
            return 0;
        }
    }
  2. Save the file in a new folder named CarLoans1 inside of your CSharp Lessons folder
  3. Save the file itself as Exercise.cs in the CarLoans1 folder
  4. Open the Command Prompt and switch to the CarLoans1 folder that contains the above exercise.cs file
  5. To compile the exercise, type: csc /reference:Microsoft.VisualBasic.dll Exercise.cs and press Enter
  6. To execute the application, type Exercise and press Enter
  7. Process an order. Here is an example:
     
     -=- Car Loan Application -=-
    Enter the following pieces of information
    
    Applicant Information
    Full Name:     James Watts
    Employer Name: Wattson Enterprises
    Home Phone:    (202) 374-4738
    Work Phone:    (301) 894-4789
    Loan Estimation
    Amount of Loan: 12500
    Interest Rate(0 to 100): 10.25
    Number of Months: 48
     -=-=-=-=-=-=-=-=-=-=-=-=-=-=
     -=- Car Loan Application -=-
     -=-=-=-=-=-=-=-=-=-=-=-=-=-=
    Applicant Information
    Full Name:     James Watts
    Employer Name: Wattson Enterprises
    Home Phone:    (202) 374-4738
    Work Phone:    (301) 894-4789
    Loan Estimation
    Loan Amount:      $12,500.00
    Interest Rate:    10.25 %
    Number of Months: 48.00
    Monthly Payment:  $315.84
  8. Return to Notepad
 

File Initialization

The FileInfo class is equipped with one constructor whose syntax is:

public FileInfo(string fileName);

This constructor takes as argument the name of a file or its complete path. If you provide only the name of the file, the compiler would consider the same directory of its project. Here is an example:

FileInfo fleMembers = new FileInfo("First.txt");

Alternatively, if you want, you can provide any valid directory you have access to. In this case, you should provide the complete path.

 

File Creation

The FileInfo constructor is mostly meant only to indicate that you want to use a file, whether it exists already or it would be created. Based on this, if you execute an application that has only a FileInfo object created using the constructor as done above, nothing would happen.

To create a file, you have various alternatives. If you want to create one without writing anything in it, which implies creating an empty file, you can call the FileInfo.Create() method. Its syntax is:

public FileStream Create();

This method simply creates an empty file. Here is an example of calling it:

FileInfo fleMembers = new FileInfo("First.txt");
fleMembers.Create();

The FileInfo.Create() method returns a FileStream object. You can use this returned value to write any type of value into the file, including text. If you want to create a file that contains text, an alternative is to call the FileInfo.CreateText() method. Its syntax is:

public StreamWriter CreateText();

This method directly returns a StreamWriter object. You can use this returned object to write text to the file.

 

File Existence

When you call the FileInfo.Create() or the FileInfo.CreateText() method, if the file passed as argument, or as the file in the path of the argument, exists already, it would be deleted and a new one would be created with the same name. This can cause the right file to be deleted. Therefore, before creating a file, you may need to check whether it exists already. To do this, you can check the value of the Boolean FileInfo.Exists property. This property holds a true value if the file exists already and it holds a false value if the file doesn't exist or it doesn't exist in the path.

Here is an example of checking the existence of a file:

FileInfo fleMembers = new FileInfo("First.txt");
fleMembers.Create();

if( fleMembers.Exists == true )
	return;
 

Writing to a File

As mentioned earlier, the FileInfo.Create() method returns a FileStream object. You can use this to specify the type of operation that would be allowed on the file.

To write normal text to a file, you can first call the FileInfo.CreateText() method. This method returns a StreamWriter object. The StreamWriter class is based on the TextWriter class that is equipped with Write() and WriteLine() methods used to write values to a file. The Write() method writes text on a line and keeps the caret on the same line. The WriteLine() method writes a line of text and moves the caret to the next line.

After writing to a file, you should close the StreamWriter object to free the resources it was using during its operation(s).

 

Practical Learning Practical Learning: Writing to a File

  1. To allow the user to create a new employee, change the file as follows:
     
    using System;
    using System.IO;
    
    namespace CarLoan
    {
        public class Exercise
        {
    	private static void CreateNewEmployee()
    	{
    	    string employeeNumber, employeeName;
    	    FileInfo fleEmployees = new FileInfo("Employees.txt");
    	    StreamWriter 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();
    	    }
    	}
    
    	static int Main()
    	{
    	    Console.Write("Do you want to hire a new employee(0=No/1=Yes)? ");
    	    int answer = int.Parse(Console.ReadLine());
    
    	    if( answer == 1 )
    		CreateNewEmployee();
    /*
    	    string applicantName, employerName;
    	    string homePhone, workPhone;
    	    double loanAmount, interestRate, monthlyPayment, periods;
    
    	    . . . No Change
    */
    	    return 0;
    	}
        }
    }
  2. Return to the Command Prompt and compile the application by typing
     
    csc /reference:Microsoft.VisualBasic.dll /out:"Car Loan".exe exercise.cs
  3. Press Enter
  4. Execute the application by typing "Car Loan" and pressing Enter
  5. Accept to create an employee and remember the employee number you specify. Here is an example:
     
    Do you want to hire a new employee(0=No/1=Yes)? 1
    Hiring New Employee
    Enter Employee Number as 00-000: 44-228
    Enter Employee Name: Johnny Olney
  6. Return to Notepad
 

Appending to a File

You may have created a text-based file and written to it. If you open such a file and find out that a piece of information is missing, you can add that information to the end of the file. To do this, you can call the FileInfo.AppenText() method. Its syntax is:

public StreamWriter AppendText();

When calling this method, you can retrieve the StreamWriter object that it returns, then use that object to add new information to the file.

 

Practical Learning Practical Learning: Appending to a File

  1. To allow the user to add more employees to the file that holds their names, change the source file as follows:
     
    using System;
    using System.IO;
    
    namespace CarLoan
    {
        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();
    	    }
    	}
    
    	static int Main()
    	{
    	    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 applicantName, employerName;
    	    
    	    . . . No Change
    */
    	    return 0;
    	}
        }
    }
  2. Return to the Command Prompt and compile the application by typing
     
    csc /reference:Microsoft.VisualBasic.dll /out:"Car Loan".exe exercise.cs
  3. Press Enter
  4. Execute the application by typing "Car Loan" and pressing Enter
  5. Accept to create an employee. Here is an example:
     
    Do you want to hire a new employee(0=No/1=Yes)? 1
    Hiring New Employee
    Enter Employee Number as 00-000: 72-604
    Enter Employee Name: Ernest Barzan
    
    Do you want to hire a new employee(0=No/1=Yes)? 1
    Hiring New Employee
    Enter Employee Number as 00-000: 25-118
    Enter Employee Name: Gertrude Nunn
    
    Do you want to hire a new employee(0=No/1=Yes)? 1
    Hiring New Employee
    Enter Employee Number as 00-000: 86-225
    Enter Employee Name: Hermine Pampam
    Do you want to hire a new employee(0=No/1=Yes)? 0
    
    C:\CSharp Lessons\CarLoans1>
  6. Return to Notepad
 
 

Previous Copyright © 2005-2016, FunctionX Next