Exception Handling in File Processing

Introduction

In previous lessons, to handle exceptions, we were using the try, catch, and throw keywords. These allowed us to perform normal operations in a try section and then handle an exception, if any, in a catch block. We also mentioned that, when you create a stream, the operating system must allocate resources and dedicate them to the file processing operations. Additional resources may be provided for the object that is in charge of writing to, or reading from, the stream. We also saw that, when the streaming was over, we should free the resources and give them back to the operating system. To do this, we called the Close() method of the variable that was using resources.

Practical LearningPractical Learning: Introducing File Processing

Finally

More than any other assignment, file processing is in prime need of exception handling. During file processing, there are many things that can go wrong. For this reason, the creation and/or management of streams should be performed in a try block to get ready to handle exceptions that would occur. Besides actually handling exceptions, the C# language provides a special keyword used to free resources. This keyword is finally.

The finally keyword is used to create a section of an exception. Like catch, a finally block cannot exist by itself. It can be created following a try section. The formula used is:

try
{
}
finally
{
}

Based on this, the finally section has a body of its own, delimited by its curly brackets. Like catch, the finally section is created after the try section. Unlike catch, finally never has parentheses and never takes arguments. Unlike catch, the finally section is always executed. Because the finally clause always gets executed, you can include any type of code in it but it is usually appropriate to free the resources that were allocated previously. In the same way, you can use a finally section to free resources used when reading from a stream. Here are examples:

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

        private void btnSave_Click(object sender, EventArgs e)
        {
            string Filename = "Employees.spr";
            
            FileStream fstPersons = new FileStream(Filename,
                                                   FileMode.Create);
            BinaryWriter wrtPersons = new BinaryWriter(fstPersons);

            try
            {
                wrtPersons.Write(txtPerson1.Text);
                wrtPersons.Write(txtPerson2.Text);
                wrtPersons.Write(txtPerson3.Text);
                wrtPersons.Write(txtPerson4.Text);

                txtPerson1.Text = "";
                txtPerson2.Text = "";
                txtPerson3.Text = "";
                txtPerson4.Text = "";
            }
            finally
            {
                wrtPersons.Close();
                fstPersons.Close();
            }
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            string Filename = "Employees.spr";
            FileStream fstPersons = new FileStream(Filename, FileMode.Open);
            BinaryReader rdrPersons = new BinaryReader(fstPersons);

            try
            {
                txtPerson1.Text = rdrPersons.ReadString();
                txtPerson2.Text = rdrPersons.ReadString();
                txtPerson3.Text = rdrPersons.ReadString();
                txtPerson4.Text = rdrPersons.ReadString();
            }
            finally
            {
                rdrPersons.Close();
                fstPersons.Close();
            }
        }
    }
}

Of course, since the whole block of code starts with a try section, it is used for exception handling. This means that you can add the necessary and appropriate catch section(s) (but you don't have to).

.NET Framework Exception Handling for File Processing

In the previous sections as our introduction to file processing, we behaved as if everything was alright. Unfortunately, file processing can be very strict in its operations. Based on this, the .NET Framework provides various Exception-oriented classes to deal with almost any type of exception you can think of.

One of the most important aspects of file processing is the name of the file that will be dealt with. In some cases, you can provide this name to the application. In some other cases, you would let the user specify the name of the path. Regardless of how the name of the file would be provided to the operating system, when this name is acted upon, the compiler is asked to work on the file. If the file doesn't exist, the operation cannot be carried. Furthermore, the compiler would throw an error. Here is an example:

private void btnOpen_Click(object sender, EventArgs e)
{
    string Filename = "contractors.spr";
    FileStream fstPersons = null;
    BinaryReader rdrPersons = null;

    fstPersons = new FileStream(Filename, FileMode.Open);
    rdrPersons = new BinaryReader(fstPersons);

    try
    {
        txtPerson1.Text = rdrPersons.ReadString();
        txtPerson2.Text = rdrPersons.ReadString();
        txtPerson3.Text = rdrPersons.ReadString();
        txtPerson4.Text = rdrPersons.ReadString();
    }
    finally
    {
        rdrPersons.Close();
        fstPersons.Close();
    }
}

Here is an example of an error that this would produce:

There are many other exceptions that can be thrown as a result of something going bad during file processing:

FileNotFoundException: This exception is thrown when a file has not been found. Here is an example of handling it:

private void btnOpen_Click(object sender, EventArgs e)
{
    string Filename = "contractors.spr";

    try
    {
        FileStream fstPersons = new FileStream(Filename, FileMode.Open);
        BinaryReader rdrPersons = new BinaryReader(fstPersons);

        try
        {
            txtPerson1.Text = rdrPersons.ReadString();
            txtPerson2.Text = rdrPersons.ReadString();
            txtPerson3.Text = rdrPersons.ReadString();
            txtPerson4.Text = rdrPersons.ReadString();
        }
        finally
        {
            rdrPersons.Close();
            fstPersons.Close();
        }
    }
    catch(FileNotFoundException ex)
    {
        Console.Write("Error: " + ex.Message);
        MessageBox.Show(" May be the file doesn't exist or you typed it wrong!");
    }
}

Here is an example of what this would produce:

IOException: As mentioned already, during file processing, anything could go wrong. If you don't know what caused an error, you can handle the IOException exception.

Disposing of a Streaming Object

File processing is usually a resource-intensive operation. Therefore, whenever you finish performing streaming operations, you should free the resources you were using. We saw that, to do this, you can call the Close() method of the class you were using to perform the operation. Of course, C# provides a better solution.

All classes, or their parents, that are used for streaming operations implement the IDisposable interface. For example, Stream, the parent of many streaming classes, starts as follows:

public abstract class Stream : MarshalByRefObject, IAsyncDisposable, IDisposable

The BinaryReader class starts as follows:

public class BinaryReader : IDisposable

The BinaryReader class starts as follows:

public class BinaryWriter : IAsyncDisposable, IDisposable

As you may know already, when a class implements the IDisposable interface, you can use the using() operator to dispose of the resources that its object are using. Therefore, instead of using the finally clause to close the stream, you can include stream in a using section.

Here are examples:

using System.IO;

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

            StringBuilder sbDirectory = new StringBuilder(@"C:\Gas Utility Company");

            /* If you want to use a drive other than the C:> drive, 
             * change the letter in the following line. */
            Directory.CreateDirectory(sbDirectory.ToString());
        }

        private void chkOpenSave_CheckedChanged(object sender, EventArgs e)
        {
            if (chkOpenSave.Checked == false)
            {
                btnSave.Visible = true;
                btnOpen.Visible = false;
                chkOpenSave.Text = "Open Existing Record";
                gbxGasMeter.Text = "Create New Gas Meter Record";

                MessageBox.Show("Please provide the values for the gas meter and then click Save.", "Gas Utility Company");
            }
            else // if (chkOpenSave.Checked == true)
            {
                btnSave.Visible = false;
                btnOpen.Visible = true;
                chkOpenSave.Text = "Create New Record";
                gbxGasMeter.Text = "Open Existing Gas Meter Record";

                MessageBox.Show("Please click the Open button and select the desired file.", "Gas Utility Company");
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtMeterNumber.Text))
            {
                MessageBox.Show("You must type a (unique) number for the gas meter.", "Gas Utility Company");

                // If the user doesn't provide a meter number, don't do nothing.
                return;
            }

            if (string.IsNullOrEmpty(txtMake.Text))
            {
                MessageBox.Show("Please enter the name of the gas meter manufaturer.", "Gas Utility Company");

                // If the user doesn't provide the meter manufaturer, don't do nothing.
                return;
            }

            if (string.IsNullOrEmpty(txtModel.Text))
            {
                MessageBox.Show("Can you identify the model of the gas meter? Type it.", "Gas Utility Company");

                // If the user doesn't provide the meter model, don't do nothing.
                return;
            }

            if (string.IsNullOrEmpty(txtCounterValue.Text))
                MessageBox.Show("Type the initial or current reading counter on the gas meter.", "Gas Utility Company");

            /* We already have a directory where we will save the files of this application:
             * Company File Repository: C:\Gas Utility Company */
            /* Each gas meter will have its own file. The name of the file of
             * a gas meter will be the meter number and the "gms" extension. */

            sfDialogBox.FileName = txtMeterNumber.Text + ".gms";
            // sfDialogBox.InitialDirectory = @"C:\Gas Utility Company";

            if (sfDialogBox.ShowDialog() == DialogResult.OK)
            {
                /* Create a file stream that can be used to create a new file, 
                 * that can access a file to write to it, and that can allow 
                 * clients (such as other/networked computers to write to it. */
                using (FileStream fsGasMeters = new FileStream(sfDialogBox.FileName, FileMode.Create, FileAccess.Write, FileShare.Write))
                {
                    using (BinaryWriter bwGasMeter = new BinaryWriter(fsGasMeters))
                    {
                        // Get each value from the form and write it to the file
                        bwGasMeter.Write(txtMeterNumber.Text);
                        bwGasMeter.Write(txtMake.Text);
                        bwGasMeter.Write(txtModel.Text);
                        bwGasMeter.Write(mcMeterReadingDate.SelectionStart.ToShortDateString());
                        bwGasMeter.Write(txtCounterValue.Text);

                        // After saving the file, reset the form by setting the initial/empty values to the controls
                        txtMake.Text = "";
                        txtModel.Text = "";
                        txtMeterNumber.Text = "";
                        mcMeterReadingDate.SelectionStart = DateTime.Today;
                        txtCounterValue.Text = "0";
                    }
                }
            }
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (ofDialogBox.ShowDialog() == DialogResult.OK)
            {
                using (FileStream fsGasMeters = new FileStream(ofDialogBox.FileName,
                                                               FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (BinaryReader brGasMeter = new BinaryReader(fsGasMeters))
                    {
                        txtMeterNumber.Text = brGasMeter.ReadString();
                        txtMake.Text = brGasMeter.ReadString();
                        txtModel.Text = brGasMeter.ReadString();
                        mcMeterReadingDate.SelectionStart = DateTime.Parse(brGasMeter.ReadString());
                        txtCounterValue.Text = brGasMeter.ReadString();
                    }
                }
            }
        }
    }
}

Information for Directories and Files

Introduction to Directory

To assist you with directory information, the .NET Framework provides a sealed class named DirectoryInfo. The DirectoryInfo class is derived from an abstract class named FileSystemInfo:

public sealed class DirectoryInfo : System.IO.FileSystemInfo

Based on this, to prepare to get some information about one or more directories, declare a variable of type DirectoryInfo.

Getting Information About a Directory

Probably the most fundamental piece of information you need about a directory is its name. When declaring a variable using the DirectoryInfo class, the class is equipped with one constructor whose syntax is:

public DirectoryInfo (string path);

When declaring the variable, pass its path as argument to this constructor.

Creating a Directory

To let you create a directory, the DirectoryInfo class is equipped with a method named Create. Its syntax is simply:

public void Create();

When you call this method, the compiler checks the path that its DirectoryInfo object was given. If there is something wrong with the path (invalid or inexistant drive, wrong characters in the name of the indicated folder, etc), the creation fails and the compiler throws an IOException exception. If the path is appropriate, the compiler checks if that directory exists already. If that's the case, nothing else is done. If the directory doesn't exist, the compiler creates the directory. Here is an example:

using System.IO;
using System.Windows.Forms;

namespace Exercises
{
    public partial class Exercise : Form
    {
        DirectoryInfo diCompanyRepository = null;

        public Exercise()
        {
            InitializeComponent();

            /* If you want to use a drive other than the C:> drive, 
             * change the letter in the following line. */
            // Specify the directory where the company's fille will be stored:
            diCompanyRepository = new DirectoryInfo(@"C:\Gas Utility Company");

            diCompanyRepository.Create();
        }
    }
}

Creating a Sub-Directory

To let you create a directory inside an existing folder, the DirectoryInfo class is equipped with a method named CreateSubdirectory. Its syntax is simply:

public System.IO.DirectoryInfo CreateSubdirectory(string path);

When you call this method, the compiler checks the folder that was given to the DirectoryInfo object. If the directory exists already inside the given folder, nothing would happen. If that sub-folder doesn't exist, the compiler would create it. Here are examples:

using System.IO;
using System.Windows.Forms;

namespace GasUtilityCustomers1
{
    public partial class Form1 : Form
    {
        DirectoryInfo diGasMeters = null;
        DirectoryInfo diCustomers = null;
        DirectoryInfo diCompanyRepository = null;

        public Form1()
        {
            InitializeComponent();

            /* If you want to use a drive other than the C:> drive, 
             * change the letter in the following line. */
            // Specify the directory where the company's fille will be stored:
            diCompanyRepository = new DirectoryInfo(@"C:\Gas Utility Company");

            diCompanyRepository.Create();
            diCustomers = diCompanyRepository.CreateSubdirectory("Customers");
            diGasMeters = diCompanyRepository.CreateSubdirectory("Gas Meters");
        }
    }
}

File Information

Introduction

In its high level of support for file processing, the .NET Framework provides a sealed class named FileInfo. This class is equipped to handle various types of file-related operations including creating, copying, moving, renaming, or deleting a file. Like the DirectoryInfo class, FileInfo is based on FileSystemInfo:

public sealed class FileInfo : System.IO.FileSystemInfo

Initializing File Information

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:

public partial class Exercise : Form
{
    private void btnSave_Click(object sender, EventArgs e)
    {
        FileInfo flePeople = new FileInfo("People.txt");
    }
}

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

Creating a File

The FileInfo constructor is mostly meant 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 options. To let you create a file without writing anything in it, which implies creating an empty file, the FileInfo class is equipped with a method named Create. 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();
}

The Files of a Directory

To let you get the list of files included in a folder, the DirectoryInfo class is equipped with an overloaded method named GetFiles. The DirectoryInfo.GetFiles() method comes in four versions. One of the versions takes 0 argument. Its syntax is:

public System.IO.FileInfo[] GetFiles();

As you can see, the DirectoryInfo.GetFiles() method returns a list of the files in a directory, as an array. Here is an example of calling this method:

private void btnFileInformation_Click(object sender, EventArgs e)
{
    DirectoryInfo diGasMeters = new DirectoryInfo(@"C:\Gas Utility Company");
    FileInfo[] files = diGasMeters.GetFiles();

    MessageBox.Show("The number of files in the directory is " + files.Length,
                    "Gas Utility Company");
}

After calling the method, you can access each file using a loop operator and do what you want.

The above version of the DirectoryInfo.GetFiles() method produces all the files in the designated directory. If you have some way to apply a criterion to select only some files, the class provides the following version of the method:

public System.IO.FileInfo[] GetFiles (string searchPattern);

This version is very easy and flexible to use. You can pass a common character that can be found in the names of the files, you can pass an expression that is common to a group of files, or you can pass the exact name of the file to locate.

The Name of a File

A computer file is primarily known for its name. To let you get the name of the file (without its path), the FileSystemInfo class is equipped with a property named Name:

public override string Name { get; }

The classes that are based on the FileSystemInfo class inherit and override this property. Here is an example of accessing this property:

private void btnFileInformation_Click(object sender, EventArgs e)
{
    DirectoryInfo diGasMeters = new DirectoryInfo(@"C:\Gas Utility Company");
    FileInfo[] files = diGasMeters.GetFiles();

    int i = 0;

    while(i < files.Length)
    {
        MessageBox.Show("File name: " + files[i].Name,
                        "Gas Utility Company");
        i++;
    }
}

The Full Name of a File

If you are trying to get the name of a file and its location, the FileSystemInfo class is equipped with a property named FullName:

public virtual string FullName { get; }

The classes that inherit from FileSystemInfo also inherit this property. The FileSystemInfo.FullName property includes the path (where the file is located) and its name.

Stream Writing and Reading

Creating Text File

To assist you in creating text-based files, the .NET Framework provides an abstract class named TextWriter. This class implements the IDisposable interface. This means that you can use the using operator on an object of a class that derives from the TextWriter class.

To assist you in writing text to a file, the .NET Framework provides a class named StreamWriter. This class is derived from the TextWriter class:

public class StreamWriter : System.IO.TextWriter

One way to use this class is to first create a text-based file. To assist you with this, the FileInfo class is equipped with a method named CreateText. Its syntax is:

public StreamWriter CreateText();

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

Writing Text to a File

To write normal text to a file, you can first call the FileInfo.CreateText() method that returns a StreamWriter object. The StreamWriter class is based on the TextWriter class that is equipped with methods named Write and WriteLine. These methods are 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). Here is an example:

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 = "";
    }
}

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 support this, the FileInfo class is equipped with a method named AppenText. 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.

Reading Text from a File

As opposed to writing to a file, you can read from it. To assist you with this, the .NET Framework provides an abstract class named TextReader. This class also implements the IDisposable interface, which means that it makes the using operator available. To assist you in reading text from a file, the .NET Framework provides a class named StreamReader. It is derived from TextReader:

public class StreamReader : System.IO.TextReader

As one way to use the StreamReader class, the FileInfo class is equipped with a method named OpenText(). Its syntax is:

public StreamReader OpenText();

This method returns a StreamReader object. You can then use this object to read the lines of a text file. To make it possible, the TextReader class is equipped with two methods named Read and ReadLine. The TextReader.Read() method reads a line of text and keeps the caret on that line. The TextReader.ReadLine() method reads a line of text but moves the caret to the next line. Here is an example:

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

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

Creating a Stream for Text Writing

In previous sections, we were using FileInfo to create a file and get a StreamWriter object. In reality, the StreamWriter class itself is equipped to create a file and write text to it. The StreamWriter class is equipped with various constructors. One of the constructors uses the following syntax:

public StreamWriter (System.IO.Stream stream);

This constructor takes a Stream-based object as argument. Once you have declared and initialized the StreamWriter variable, you can call any of its methods to write text to the file.

A Stream for Text Reading

Although we have previously first create a FileInfo object to create a file and get a StreamReader object, the StreamReader class provides its own means to create a file and write text to it. The StreamReader class has many constructors. One of the constructors uses the following syntax:

public StreamReader(System.IO.Stream stream);

This constructor takes a Stream-based object as argument. You can then use the StreamReader object to get text from the file.

Routine Operations on Files

Checking File Existence

Some operations require that you create a new file and some others need an existing file. In some cases. In some cases, before creating a file, you may first need to check whether the file exists already or not or you may want to make sure the file exists in order to open it. Various classes allow you to perform this operation. The static File class is equipped with a method named Exists. Its syntax is:

public static bool Exists (string path);

To check whether a file exists and/or name to this method. If the method returns true, the file exists already. If the file doesn't exist or the compiler can' find it one way or another, the method returns false.

As an alternative to check the existing of a file, the FileInfo class inherits a Boolean property named Exists from its parent:

FileSystemInfo: public abstract bool Exists { get; }
FileInfo:       public override bool Exists { get; }

This time, to check the existence of a file, compare the FileInfo.Exists property to true or false. 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 using it:

using System.IO;
using System.Windows.Forms;

namespace FileProcessing
{
    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");
        }
    }
}

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 a method named Open. This method 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.

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.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2008-2024, FunctionX Friday 10 June 2022 Home