Home

Files Operations

 

Files Information

 

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 LearningPractical Learning: Introducing File Information

  1. To start a new application, on the main menu, click File -> New -> Project...
  2. In the middle list, click Windows Forms Application
  3. Set the name to WattsALoan1
  4. In the Properties window, change the form's Text to Watts A Loan
  5. In the Common Controls section of the Toolbox, click ToolTip and click the form
  6. Design the form as follows:
     
    Watts A Loan
    Control Name Text ToolTip on toolTip1
    Label Label   Acnt #:  
    Label Label   Customer Name:  
    Label Label   Customer:  
    TextBox TextBox txtAccountNumber   Account number of the customer requesting the loan
    TextBox TextBox txtCustomerName   Name of the customer requesting the loan
    Label Label   Empl #:  
    Label Label   Employee Name:  
    Label Label   Prepared By:  
    TextBox TextBox txtEmployeeNumber   Employee number of the clerk preparing the loan
    TextBox TextBox txtEmployeeName   Name of the clerk preparing the loan
    Button Button btnNewEmployee   Used to add a new employee to the company
    Label Label   Loan Amount:  
    TextBox TextBox txtLoanAmount   Amount of loan the customer is requesting
    Label Label   Interest Rate:  
    TextBox TextBox txtInterestRate   Annual percentage rate of the loan
    Label Label   %  
    Label Label   Periods  
    TextBox TextBox   txtPeriods The number of months the loan is supposed to last
    Button Button btnCalculate Calculate Used to calculate the monthly payment
    Label Label   Monthly Payment:  
    TextBox TextBox txtMonthlyPayment   The minimum amount the customer should pay every month
    Button Button btnClose Close Used to close the form
  7. Double-click the Calculate button and implement its event as follows:
    System::Void btnCalculate_Click(System::Object^  sender, System::EventArgs^  e)
    {
        double Principal    = 0.00,
               InterestRate = 0.00,
               InterestEarned,
    	   FutureValue,
    	   MonthlyPayment;
        double Periods = 0.00;
    
        try {
            Principal = double::Parse(txtLoanAmount->Text);
        }
        catch(FormatException ^)
        {
            MessageBox::Show(L"The value you entered for the "
                             L"principal is not valid");
        }
    
        try {
            InterestRate = double::Parse(txtInterestRate->Text);
        }
        catch(FormatException ^)
        {
            MessageBox::Show(L"Wrong Value: The interest rate must "
                             L"be a value between 0 and 100");
        }
    
        try {
            Periods = double::Parse(txtPeriods->Text);
        }
        catch(FormatException ^)
        {
            MessageBox::Show(L"You entered an invalid value for the periods");
        }
    
        double I = InterestRate / 100;
        double p = Periods / 12;
        
    	InterestEarned = Principal * I  * p;
        FutureValue    = Principal + InterestEarned;
    	MonthlyPayment = FutureValue / Periods;
    
        txtMonthlyPayment->Text = MonthlyPayment.ToString(L"F");
    }
  8. Return to the form and double-click the Close button to implement its event as follows:
    System::Void btnClose_Click(System::Object^  sender, System::EventArgs^  e)
    {
        Close();
    }

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 = gcnew FileInfo(L"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.

Practical LearningPractical Learning: Initializing a File

  1. In the top section of the Form1.h file, under the other using namespace lines, type using namespace System::IO
  2. Return to the form
  3. Double-click an unoccupied area on the body form
  4. Implement the Load event as follows:
    System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e)
    {
    	 String ^ strFilename = L"Employees.wal";
    	 FileInfo ^ fiEmployees = gcnew FileInfo(strFilename);
    }

Writing Text to a File

After creating a file, you can write one or more values to it. An example of a value is text. If you want to create a file that contains text, the FileInfo class provides a member function named CreateText . Its syntax is:

public:
    StreamWriter ^CreateText();

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

ApplicationPractical Learning: Creating a Text File

  • Change the Load event of the form as follows:
    System::Void Form1_Load(Object ^ sender, EventArgs ^ e)
    {
        String  ^ strFilename = "Employees.wal";
        FileInfo ^ fiEmployees = gcnew FileInfo(strFilename);
    
        StreamWriter stwEmployees = fiEmployees->CreateText();
    }

Writing a Value to a File

To write normal text to a file, you can first call the FileInfo::CreateText() member function. Its syntax is:

public:
    StreamWriter CreateText();

 This member function returns a StreamWriter object. The StreamWriter class is based on the TextWriter class that is equipped with the Write() and the WriteLine() member functions used to write values to a file. The Write() member function writes text on a line and keeps the caret on the same line. The WriteLine() member function 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). Here is an example:

System::Void btnSave_Click(System::Object^  sender, System::EventArgs^  e)
{
    FileInfo ^ flePeople = gcnew FileInfo("People.txt");
    StreamWriter ^ stwPeople = flePeople->CreateText();

    try
    {
        stwPeople->WriteLine(txtPerson1->Text);
        stwPeople->WriteLine(txtPerson2->Text);
        stwPeople->WriteLine(txtPerson3->Text);
        stwPeople->WriteLine(txtPerson4->Text);
    }
    finally
    {
        stwPeople->Close();

        txtPerson1->Text = "";
        txtPerson2->Text = "";
        txtPerson3->Text = "";
        txtPerson4->Text = "";
    }
}

ApplicationPractical Learning: Writing to a Text File

  • Change the Load event of the form as follows:
    System::Void Form1_Load(Object ^ sender, EventArgs ^ e)
    {
        String  ^ strFilename = "Employees.wal";
        FileInfo ^ fiEmployees = gcnew FileInfo(strFilename);
    
        StreamWriter ^ stwEmployees = fiEmployees->CreateText();
    
        // And create a John Doe employee
        try {
    	    stwEmployees->WriteLine("00-000");
    	    stwEmployees->WriteLine("John Doe");
        }
        finally
        {
    	stwEmployees.Close();
        }
    }

Appending Text 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() member function. Its syntax is:

public:
    StreamWriter ^ AppendText();

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

ApplicationPractical Learning: Writing to a Text File

  1. To create a new form, on the main menu, click Project -> Add New Item...
  2. In the middle list, click Windows Form. Set the Name to NewEmployee
  3. Click Add
  4. In the Components section of the Toolbox, click HelpProvider and click the form
  5. Design the form as follows:
     
    Watts A  Loan - New Employee
    Control Text Name HelpString On HelpProvider1
    Label Label Employee #:    
    TextBox TextBox   txtEmployeeNumber Enter an employee number as 00-000
    Label Label Employee Name:    
    TextBox TextBox   txtEmployeeName Enter employee's full name
    Button Button Create btnCreate Used to create an employee name
    Button Button Close btnClose Used to close the form
  6. Right-click the form and click View Code
  7. In the top section of the file, under the using namespace lines, type:
    #pragma once
    
    namespace WattsALoan1 {
    
    	using namespace System;
    	using namespace System::ComponentModel;
    	using namespace System::Collections;
    	using namespace System::Windows::Forms;
    	using namespace System::Data;
    	using namespace System::Drawing;
    	using namespace System::IO;
  8. Return to the New Employee form
  9. Double-click the Create button
  10. Implement its event as follows:
    System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e)
    {
        String ^ strFilename = L"Employees.wal";
        FileInfo ^ fiEmployees = gcnew FileInfo(strFilename);
    
        StreamWriter ^ stwEmployees = fiEmployees->CreateText();
    
        // And create a John Doe employee
        try {
    	    stwEmployees->WriteLine("00-000");
    	    stwEmployees->WriteLine("John Doe");
        }
        finally
        {
    	stwEmployees->Close();
        }
    }
  11. Return to the New Employee form and double-click the Close button
  12. Implement its event as follows:
    System::Void btnClose_Click(System::Object^  sender, System::EventArgs^  e)
    {
    	Close();
    }
  13. Access the Form1.h header file
  14. In the top section of the file, include the NewEmployee.h file
    #pragma once
    
    #include "NewEmployee.h"
    
    namespace WattsALoan1 {
    
    	using namespace System;
    	using namespace System::ComponentModel;
    	using namespace System::Collections;
    	using namespace System::Windows::Forms;
    	using namespace System::Data;
    	using namespace System::Drawing;
    	using namespace System::IO;
  15. Access the Form1.h [Design] tab
  16. Double-click the top New button and implement the event as follows:
    System::Void btnNewEmployee_Click(System::Object^  sender, System::EventArgs^  e)
    {
        NewEmployee ^ frmNewEmployee = gcnew NewEmployee;
    
        frmNewEmployee->ShowDialog();
    }
  17. Return to the Form1 form
  18. In the combo box on top of the Properties window, select txtEmployeeNumber
  19. On the Properties window, click the Events button and double-click Leave
  20. Implement the event as follows:
    System::Void txtEmployeeNumber_Leave(Object ^ sender, EventArgs ^ e)
    {
        String ^ strFilename = "Employees.wal";
        FileInfo ^ fiEmployees = gcnew FileInfo(strFilename);
    
        if( txtEmployeeNumber->Text == "" )
        {
            txtEmployeeName->Text = "";
            return;
        }
        else
        {
            StreamReader ^ strEmployees = fiEmployees->OpenText();
            String ^ strEmployeeNumber, ^ strEmployeeName;
            bool found = false;
    
            try
            {
                strEmployees = gcnew StreamReader(strFilename);
    
                while(strEmployees->Peek() >= 0)
                {
                    strEmployeeNumber = strEmployees->ReadLine();
    
                    if( strEmployeeNumber == txtEmployeeNumber->Text )
                    {
                        strEmployeeName = strEmployees->ReadLine();
                        txtEmployeeName->Text = strEmployeeName;
                        found = true;
                    }
                }
    
                strEmployees->Close();
    
                // 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", "Watts A Loan");
                    txtEmployeeName->Text = "";
                    txtEmployeeNumber->Focus();
                }
            }
            finally
            {
                strEmployees->Close();
            }
        }
    }
  21. Execute the application to test it
  22. First create a few employees as follows:
     
    Employee # Employee Name
    42-806 Ann Sullivan
    75-148 Hélène Mukoko
    36-222 Frank Leandro
    42-808 John Harland
  23. Process a loan
     
    Watts A Loan
  24. Close the application

Reading from a File

As opposed to writing to a file, you can read from it. To support this, the FileInfo class is equipped with a member function named OpenText. Its syntax is:

public:
    StreamReader ^ OpenText();

This member function returns a StreamReader object. You can then use this object to read the lines of a text file. Here is an example:

System::Void btnOpen_Click(System::Object^  sender, System::EventArgs^  e)
{
    String ^ Filename = "People.txt";
    FileInfo ^ flePeople = gcnew FileInfo(Filename);
    StreamReader ^ strPeople = flePeople->OpenText();

    try
    {
        txtPerson1->Text = strPeople->ReadLine();
        txtPerson2->Text = strPeople->ReadLine();
        txtPerson3->Text = strPeople->ReadLine();
        txtPerson4->Text = strPeople->ReadLine();
    }
    finally
    {
        strPeople->Close();
    }
}
 
 
 

Routine Operations on Files

 

Creating a File

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() member function. Its syntax is:

public:
    FileStream ^ Create();

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

System::Void btnSave_Click(System::Object^  sender, System::EventArgs^  e)
{
    FileInfo ^ fleMembers = gcnew FileInfo(L"First.txt");
    fleMembers->Create();
}

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() member function that is overloaded with three versions. Their syntaxes are:

public:
    FileStream^ Open(FileMode mode);
    FileStream^ Open(FileMode mode, FileAccess access);
    FileStream^ Open(FileMode mode, FileAccess access, FileShare share);

You can select one of these member functions, depending on how you want to open the file, using the options for file mode, file access, and file sharing. Each version of this member function 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.

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() member function 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 the Read() and the ReadLine() member functions. As done for the StreamWriter class, after using a StreamReader object, make sure you close it.

Checking File Existence

When you call the FileInfo::Create() or the FileInfo::CreateText() member function, 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:

System::Void btnSave_Click(System::Object^  sender, System::EventArgs^  e)
{
    FileInfo ^ fleMembers = gcnew FileInfo(L"First.txt");
    fleMembers->Create();

    if( fleMembers.Exists == true )
	return;
}

Practical LearningPractical Learning: Creating a Text File

  • Change the Load event of the form as follows:
    System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e)
    {
        String ^ strFilename = L"Employees.wal";
        FileInfo ^ fiEmployees = gcnew FileInfo(strFilename);
    
        // If the employees file was not created already,
        // then create it
        if( !fiEmployees->Exists )
        {
    	 StreamWriter ^ stwEmployees = fiEmployees->CreateText();
        }
    }

Writing to a File

As mentioned earlier, the FileInfo::Create() member function 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() member function. This member function returns a StreamWriter object. The StreamWriter class is based on the TextWriter class that is equipped with the Write() and the WriteLine() member functions used to write values to a file. The Write() member function writes text on a line and keeps the caret on the same line. The WriteLine() member function 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 LearningPractical Learning: Writing to a Text File

  • Change the Load event of the form as follows:
    System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e)
    {
    	 String ^ strFilename = L"Employees.wal";
    	 FileInfo ^ fiEmployees = gcnew 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(L"00-000");
    		 stwEmployees->WriteLine(L"John Doe");
    	    }
    	    finally
    	    {
    		 stwEmployees->Close();
    	    }
    	 }
    }

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() member function. Its syntax is:

public:
    StreamWriter ^ AppendText();

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

Practical LearningPractical Learning: Writing to a Text File

  1. To create a new form, on the main menu, click Project -> Add New Item...
  2. In the middle list, click Windows Form
  3. Set the Name to NewEmployee and click Add
  4. Design the form as follows:
     
    Control Text Name
    Label Employee #:
    TextBox txtEmployeeNumber
    Label Employee Name:
    TextBox txtEmployeeName
    Button Create btnCreate
    Button Close btnClose
  5. Right-click the form and click View Code
  6. In the top section of the file, under the using using lines, type
    using namespace System::IO;
  7. Return to the New Employee form and double-click the Create button
  8. Implement its event as follows:
    System::Void btnCreate_Click(System::Object^  sender, System::EventArgs^  e)
    {
    	 String ^ strFilename = L"Employees.wal";
    	 FileInfo ^ fiEmployees = gcnew FileInfo(strFilename);
    	 StreamWriter ^ stwEmployees = nullptr;
    
    	 // 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 = L"";
    	 txtEmployeeName->Text = L"";
    	 txtEmployeeNumber->Focus();
    }
  9. Return to the New Employee form and double-click the Close button
  10. Implement its event as follows:
    System::Void btnClose_Click(System::Object^  sender, System::EventArgs^  e)
    {
    	 Close();
    }
  11. Access the Form1 form
  12. Double-click the top New button
  13. In the top section of the file, under the #pragma once line, type
     
    #include "NewEmployee.h"
  14. Scroll down and implement its Click event as follows:
    System::Void btnNewEmployee_Click(System::Object^  sender, System::EventArgs^  e)
    {
        NewEmployee ^ frmNewEmployee = gcnew NewEmployee;
    
        frmNewEmployee->ShowDialog();
    }
  15. Return to the form
  16. In the combo box on top of the Properties window, select txtEmployeeNumber
  17. On the Properties window, click the Events button and double-click Leave
  18. Implement the event as follows:
    System::Void txtEmployeeNumber_Leave(System::Object^  sender,
    				     System::EventArgs^  e) 
    {
        String ^ strFilename = L"Employees.wal";
        FileInfo ^ fiEmployees = gcnew FileInfo(strFilename);
    
        if(fiEmployees->Exists )
        {
    	if( txtEmployeeNumber->Text == L"" )
    	{
    		 txtEmployeeName->Text = L"";
    		 return;
    	}
    	else
    	{
    	   StreamReader ^ strEmployees = fiEmployees->OpenText();
    	   String ^ strEmployeeNumber, ^ strEmployeeName;
    	   bool found = false;
    
    	   try {
    		 while( 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(L"No employee with that number was found");
    		 	 	     txtEmployeeName->Text = L"";
    				     txtEmployeeNumber->Focus();
    		 }
    	    }
    	    finally
    	    {
    		 strEmployees->Close();
    	    }
    	 }
        }
    }
  19. Execute the application to test it
  20. 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
  21. Process a loan
     
    Watts A Loan
     
    Watts A Loan
     
    Watts A Loan
  22. Close 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() member function. Its syntax is:

public:
    virtual void Delete() override;

Here is an example:

FileInfo ^ fleMembers = gcnew FileInfo(L"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() member function that is overloaded with two versions. The first version has the following syntax:

public:
    FileInfo ^ CopyTo(String ^ destFileName);

When calling this member function, specify the path or directory that will be the destination of the copied file. Here is an example:

FileInfo ^ fleMembers = gcnew FileInfo(L"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() member function, 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 member function. Its syntax is:

public:
    FileInfo ^ CopyTo(String ^destFileName, bool overwrite);

The first argument is the same as that of the first version of the member function. 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() member function. Its syntax is:

public:
    void MoveTo(String ^destFileName);

The argument to this member function is the same as that of the CopyTo() member function. After executing this member function, the FileInfo object would be moved to the destFileName path.

Here is an example:

FileInfo ^ fleMembers = gcnew FileInfo(L"pop.txt");
String ^ strMyDocuments =
	Environment::GetFolderPath(Environment::SpecialFolder::Personal);
fleMembers->CopyTo(String::Concat(strMyDocuments, "\\pop.txt"));

Renaming a File

If you have an existing file whose name you don't want anymore, you can rename it. To support this operation, you can call the MoveTo() member function of the FileInfo class. Here is an example:

System::Void btnRename_Click(System::Object^  sender, System::EventArgs^  e)
{
    // Get a reference to the file
    FileInfo ^ fiRename = gcnew FileInfo("C:\\Exercise1\\chat1.txt");
                
    // Rename the file
    fiRename->MoveTo("C:\\Exercise1\\BlahBlahBlah.txt");
}

To perform the same operation, the File class provides a member function named Move. Its syntax is:

public static void Move(string sourceFileName, string destFileName);

Here is an example:

System::Void btnRename_Click(System::Object^  sender, System::EventArgs^  e)
{
    File::Move("C:\\Exercise\\Soho.txt", "C:\\Exercise\\Whatever.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 get accessor of the FileSystemInfo::CreationTime property. This would be done as follows:

System::Void btnDateCreated_Click(System::Object^  sender, System::EventArgs^  e)
{
    FileInfo ^ fExercise = gcnew FileInfo("C:\\Exercise1\\Exercise.txt");
    txtDateCreated->Text = fExercise->CreationTime.ToLongTimeString();
}

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 accessory 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. Here is an example:

System::Void btnDateCreated_Click(System::Object^  sender, System::EventArgs^  e)
{
    FileInfo ^ fExercise = gcnew FileInfo("C:\\Exercise1\\Exercise.txt");
    txtDateCreated->Text = fExercise->LastWriteTime.ToLongTimeString();
}

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.

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:

txtFileName->Text = "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 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:

txtFileExtension->Text = "File Extension: " + fleLoan->Extension;

The Size of a File

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:

Console::WriteLine(L"File Size: " + fleLoan::Length.ToString());

The Directory 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.

The Full Name of a File

Besides the FileInfo::Directoryname, to know the full path to a file, you can access its FileSystemInfo::FullName property. Here is an example:

System::Void btnFileName_Click(System::Object^  sender, System::EventArgs^  e)
{
	FileInfo ^ fExercise = gcnew FileInfo("C:\\Exercise1\\Exercise.txt");
	txtFileName->Text = fExercise->FullName;
}

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 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 a FileAttributes object and assign it to the FileSystemInfo.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.

 
 
   
 

Home Copyright © 2010-2016, FunctionX