Home

Microsoft Visual C# Programming: Files Operations

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

public FileStream Create();

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

private void btnSave_Click(object sender, EventArgs e)
{
    FileInfo flePeople = new FileInfo("People.txt");
    flePeople.Create();
}

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 Application
  3. Set the name to WattsALoan2
  4. In the Properties window, change the form's Text to Watts A Loan
  5. To be able to use the Visual Basic library, in the Solution Explorer, right-click WattsALoan1 and click Add Reference...
  6. In the .NET property page, click Microsoft.VisualBasic
  7. Click OK
  8. Design the form as follows:
     

    Control Name Text
    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  
    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
  9. Double-click the Calculate button and implement its event as follows:
    private void btnCalculate_Click(object sender, EventArgs e)
    {
        double LoanAmount = 0.00D,
               InterestRate = 0.00D,
               Periods = 0.00D,
               MonthlyPayment = 0.00D;
    
        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");
        }
    }
  10. Return to the form and double-click the Close button to implement its event as follows:
    private void btnClose_Click(object sender, EventArgs e)
    {
        Close();
    }
  11. Return to the form
  12. Double-click an unoccupied area on the body form
  13. Scroll up completely and, under the other using lines, type using System.IO;
  14. Scroll down complement and change the Load event of the form as follows:
    private void Form1_Load(object sender, EventArgs e)
    {
        string  strFilename = "Employees.wal";
        FileInfo  fiEmployees = new FileInfo(strFilename);
    }
  15. Change the Load event of the form as follows:
    private void Form1_Load(object sender, EventArgs e)
    {
        string  strFilename = "Employees.wal";
        FileInfo fiEmployees = new FileInfo(strFilename);
    
        StreamWriter stwEmployees = fiEmployees.CreateText();
    }
  16. Change the Load event of the form as follows:
    private void Form1_Load(object sender, EventArgs e)
    {
        string  strFilename = "Employees.wal";
        FileInfo fiEmployees = new FileInfo(strFilename);
    
        StreamWriter stwEmployees = fiEmployees.CreateText();
    
        // And create a John Doe employee
        try {
    	    stwEmployees.WriteLine("00-000");
    	    stwEmployees.WriteLine("John Doe");
        }
        finally
        {
    	stwEmployees.Close();
        }
    }
  17. To create a new form, on the main menu, click Project -> Add Windows Form...
  18. In the middle list, make sure Windows Form is selected. Set the Name to NewEmployee and click Add
  19. Design the form as follows:

    Control Text Name
    Label Employee #:  
    TextBox   txtEmployeeNumber
    Label Employee Name:  
    TextBox   txtEmployeeName
    Button Create btnCreate
    Button Close btnClose
  20. Right-click the form and click View Code
  21. In the top section of the file, under the using using lines, type using System.IO;
  22. Return to the New Employee form and double-click the Create button
  23. Implement its event as follows:
    private void btnCreate_Click(object sender, EventArgs e)
    {
        string  strFilename = "Employees.wal";
        FileInfo  fiEmployees = new FileInfo(strFilename);
        StreamWriter  stwEmployees = null;
    
        stwEmployees= fiEmployees.AppendText();
    				 
        try {
    	 stwEmployees.WriteLine(txtEmployeeNumber.Text);
    	 stwEmployees.WriteLine(txtEmployeeName.Text);
        }
        finally
        {
    	 stwEmployees.Close();
        }
    
        txtEmployeeNumber.Text = "";
        txtEmployeeName.Text = "";
        txtEmployeeNumber.Focus();
    }
  24. Return to the New Employee form and double-click the Close button
  25. Implement its event as follows:
    private void btnClose_Click(object sender, EventArgs e)
    {
        Close();
    }
  26. Access the Form1 form
  27. Double-click the top New button and implement the event as follows:
    private void btnNewEmployee_Click(object sender, EventArgs e)
    {
        NewEmployee  frmNewEmployee = new NewEmployee();
    
        frmNewEmployee.ShowDialog();
    }
  28. Return to the form
  29. In the combo box on top of the Properties window, select txtEmployeeNumber
  30. On the Properties window, click the Events button and double-click Leave
  31. Implement the event as follows:
    private void txtEmployeeNumber_Leave(object sender, EventArgs e)
    {
        string strFilename = "Employees.wal";
        FileInfo fiEmployees = new FileInfo(strFilename);
    
        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();
            }
        }
    }
  32. Execute the application to test it
  33. 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
  34. Process a loan

    Watts A Loan

  35. Close the application
  36. Change the Load event of the form as follows:
    private void Form1_Load(object sender, EventArgs e)
    {
        string  strFilename = "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();
    	}
        }
    }
  37. Open the New Employee form and change its Create event as follows:
    private void btnCreate_Click(object sender, EventArgs e)
    {
        string  strFilename = "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();
    }
  38. Change the Leave event of the Employee Number as follows:
    private void txtEmployeeNumber_Leave(object sender, EventArgs e)
    {
        string strFilename = "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();
                }
            }
        }
    }
  39. Execute the application to test it
  40. 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
  41. Process a loan
     
    Watts A Loan
  42. Close the application

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. Their syntaxes are:

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

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

Checking File Existence

When you call 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:

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;

namespace FileProcessing2
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            FileInfo flePeople = new 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 = "";
            }
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            string Filename = "People.txt";
            FileInfo flePeople = new FileInfo(Filename);
            StreamReader strPeople = flePeople.OpenText();

            if (flePeople.Exists == true)
            {
                try
                {
                    txtPerson1.Text = strPeople.ReadLine();
                    txtPerson2.Text = strPeople.ReadLine();
                    txtPerson3.Text = strPeople.ReadLine();
                    txtPerson4.Text = strPeople.ReadLine();
                }
                finally
                {
                    strPeople.Close();
                }
            }
            else
                MessageBox.Show("There is no file named People.txt " +
                                "in the indicated location");
        }
    }
}

Practical LearningPractical Learning: Checking the Existence of a File

  1. Change the Load event of the form as follows:
    private void Form1_Load(object sender, EventArgs e)
    {
        string  strFilename = "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();
    	}
        }
    }
  2. Open the New Employee form and change its Create event as follows:
    private void btnCreate_Click(object sender, EventArgs e)
    {
        string  strFilename = "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();
    }
  3. Change the Leave event of the Employee Number as follows:
    private void txtEmployeeNumber_Leave(object sender, EventArgs e)
    {
        string strFilename = "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();
                }
            }
        }
    }
  4. Execute the application to test it
  5. 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
  6. Process a loan

    Watts A Loan

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

public override void Delete();

Here is an example:

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

You can perform the same operation using the File class. It is equipped with a method named Delete. Its syntax is:

public static void Delete(string path);

When calling this method, pass the name of, or the path (relative or complete) to, the file.

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. One of the versions 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 current user.

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

You can also copy a file using the File class that is equipped with an overloaded method named Copy. One of its syntaxes is:

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

Another syntax is as follows:

public static void Copy(string sourceFileName, string destFileName, bool overwrite);

Remember that  you can copy a file in the same directory or to a different folder.

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 a 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"));

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() method of the FileInfo class. Here is an example:

private void btnRenameFile_Click(object sender, EventArgs e)
{
    // Get a reference to the file
    FileInfo fiRename = new FileInfo(@"C:\Exercise\Something.txt");
                
    // Rename the file
    fiRename.MoveTo(@"C:\Exercise\BlahBlahBlah.txt");
}

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

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

Here is an example:

private void btnRenameFile_Click(object sender, EventArgs e)
{
    File.Move(@"C:\Exercise\Soho.txt", @"C:\Exercise\Whatever.txt");
}

Characteristics of a File

The Date and Time a File Was Created 

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, which is of type DateTime. Here is an example of using it:

DateTime dteCreationTime = fleLoan.CreationTime;
label1.Text = "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 set accessor 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, which is of type DateTime.

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, which is of type DateTime.

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

MessageBox.Show("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:

MessageBox.Show("File Size: " + fleLoan.Length.ToString());

The Path to a File

Besides its name, a file 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 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 create a FileAttributes object and assign it to the FileSystemInfo.Attributes property.

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


Home Copyright © 2010-2020, FunctionX