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.

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:

using static System.Console;
using System.IO;

namespace Exercise07
{
    public class Program
    {
        static void SaveFile()
        {
            string filename = "Employees.spr";

            FileStream fstPersons = new FileStream(filename,
                                                   FileMode.Create);
            BinaryWriter wrtPersons = new BinaryWriter(fstPersons);

            try
            {
                wrtPersons.Write("Phillippe Durell");
                wrtPersons.Write("Charlotte Katts");
                wrtPersons.Write("Robert Kroeger");
                wrtPersons.Write("Jeannette Kidds");
            }
            finally
            {
                wrtPersons.Close();
                fstPersons.Close();
            }
        }

        static void OpenFile()
        {
            string Filename = "Employees.spr";
            FileStream fstPersons = new FileStream(Filename, FileMode.Open);
            BinaryReader rdrPersons = new BinaryReader(fstPersons);

            try
            {
                WriteLine(rdrPersons.ReadString());
                WriteLine(rdrPersons.ReadString());
                WriteLine(rdrPersons.ReadString());
                WriteLine(rdrPersons.ReadString());
            }
            finally
            {
                rdrPersons.Close();
                fstPersons.Close();
            }
        }

        public static int Main(string[] args)
        {
            OpenFile();
            return 903;
        }
    }
}

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 or document. 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:

using System.IO;
using static System.Console;

namespace Exercise07
{
    public class Program
    {
        public static int Main(string[] args)
        {
            string Filename = "contractors.spr";
            FileStream fstPersons = null;
            BinaryReader rdrPersons = null;

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

            try
            {
                WriteLine(rdrPersons.ReadString());
                WriteLine(rdrPersons.ReadString());
                WriteLine(rdrPersons.ReadString());
                WriteLine(rdrPersons.ReadString());
            }
            finally
            {
                rdrPersons.Close();
                fstPersons.Close();
            }
            return 903;
        }
    }
}

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

Unhandled Exception: System.IO.FileNotFoundException: Could not find file 'F:\Users\User1\source\repos\Console\Exercise07\Exercise07\bin\Debug\contractors.spr'.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
   at System.IO.FileStream..ctor(String path, FileMode mode)
   at Exercise07.Program.Main(String[] args) in F:\Users\User1\source\repos\Console\Exercise07\Exercise07\Program.cs:line 14
Press any key to continue . . .

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:

using System.IO;
using static System.Console;

namespace Exercise07
{
    public class Program
    {
        public static int Main(string[] args)
        {
            string Filename = "contractors.spr";

            try
            {
                FileStream fstPersons = null;
                BinaryReader rdrPersons = null;

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

                try
                {
                    WriteLine(rdrPersons.ReadString());
                    WriteLine(rdrPersons.ReadString());
                    WriteLine(rdrPersons.ReadString());
                    WriteLine(rdrPersons.ReadString());
                }
                finally
                {
                    rdrPersons.Close();
                    fstPersons.Close();
                }
            }
            catch (FileNotFoundException fnfe)
            {
                WriteLine("Error: " + fnfe.Message);
                WriteLine(" May be the file doesn't exist or you typed it wrong!");
            }

            return 903;
        }
    }
}

Here is an example of what this would produce:

Error: Could not find file 'F:\Users\User1\source\repos\Console\Exercise07\Exercise07\bin\Debug\contractors.spr'.
 May be the file doesn't exist or you typed it wrong!
Press any key to continue . . .

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

Disposing of an Object

In our introduction to built-in interfaces, we saw that, when an application requires somes resources, and when you have finished using those resources, you should free them. We saw that some classes implement an interface named IDisposable. We saw that when a class implements that interface, to free the resources a class was using, you can use the using operator.

Many, in fact most, of the Stream-based classes we have used and will see implement the IDisposable interface. Therefore, instead of using the finally clause to close the stream, you can include stream in a using section. Here is an example:

using System.IO;
using static System.Console;

public class Program
{
    static void SaveFile()
    {
        string filename = "Employees1.spr";

        using (FileStream fstPersons = new FileStream(filename, FileMode.Create))
        {
            BinaryWriter wrtPersons = new BinaryWriter(fstPersons);

            try
            {
                wrtPersons.Write("Phillippe Durell");
                wrtPersons.Write("Charlotte Katts");
                wrtPersons.Write("Robert Kroeger");
                wrtPersons.Write("Jeannette Kidds");
            }
            finally
            {
                fstPersons.Close();
            }
        }
    }

    static void OpenFile()
    {
        string Filename = "Employees1.spr";

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

            try
            {
                WriteLine(rdrPersons.ReadString());
                WriteLine(rdrPersons.ReadString());
                WriteLine(rdrPersons.ReadString());
                WriteLine(rdrPersons.ReadString());
            }
            finally
            {
                fstPersons.Close();
            }
        }
    }

    public static int Main()
    {
        SaveFile();

        return 903;
    }
}

If a disposable object is nested in another disponible object, you can apply the same technique with the using operator. Here is an example:

using System.IO;
using static System.Console;

public class Program
{
    static void SaveFile()
    {
        string filename = "Employees1.spr";

        using (FileStream fstPersons = new FileStream(filename, FileMode.Create))
        {
            using (BinaryWriter wrtPersons = new BinaryWriter(fstPersons))
            {
                wrtPersons.Write("Phillippe Durell");
                wrtPersons.Write("Charlotte Katts");
                wrtPersons.Write("Robert Kroeger");
                wrtPersons.Write("Jeannette Kidds");
            }
        }
    }

    static void OpenFile()
    {
        string Filename = "Employees1.spr";

        using (FileStream fstPersons = new FileStream(Filename, FileMode.Open))
        {
            using (BinaryReader rdrPersons = new BinaryReader(fstPersons))
            {
                WriteLine(rdrPersons.ReadString());
                WriteLine(rdrPersons.ReadString());
                WriteLine(rdrPersons.ReadString());
                WriteLine(rdrPersons.ReadString());
            }
        }
    }

    public static int Main()
    {
        OpenFile();
        return 903;
    }
}

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 directry 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 method. 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;
using System.IO;

namespace GasUtilityCustomers1
{
    public class Exercise
    {
        static DirectoryInfo diCompanyRepository = null;

        public static int Main(string[] args)
        {
            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();

	    return 903;
        }
    }
}

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

using System;
using System.IO;

namespace GasUtilityCustomers1
{
    public class Exercise
    {
        static DirectoryInfo diGasMeters = null;
        static DirectoryInfo diCustomers = null;
        static DirectoryInfo diCompanyRepository = null;

        public static int Main(string[] args)
        {
            /* 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");

	    return 94;
        }
    }
}

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:

using System.IO;

public class Exercise
{
    public static int Main(string[] args)
    {
        FileInfo flePeople = new FileInfo("People.txt");

	return 905;
    }
}

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:

using System.IO;

public class Exercise
{
    public static int Main(string[] args)
    {
    	FileInfo flePeople = new FileInfo("People.txt");
    	flePeople.Create();

	return 906;
    }
}

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:

using static System.Console;
using System.IO;

namespace DrivesCharacteristics
{
    public class Exercise
    {
        public static int Main(string[] args)
        {
	    Title = "Gas Utility Company";

            DirectoryInfo diGasMeters = new DirectoryInfo(@"C:\Gas Utility Company");
            FileInfo[] files = diGasMeters.GetFiles();

            WriteLine("The number of files in the directory is " + files.Length);

	    return 907;
        }
    }
}

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 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 inherit from FileSystemInfo inherit and override this property. Here is an example of accessing this property:

using System.IO;

namespace DrivesCharacteristics
{
    public class Exercise
    {
        public static int Main(string[] args)
        {
            DirectoryInfo diGasMeters = new DirectoryInfo(@"C:\Gas Utility Company");
            FileInfo[] files = diGasMeters.GetFiles();

	    Title = "Gas Utility Company";
            int i = 0;

            while(i < files.Length)
            {
                WriteLine("File name: " + files[i].Name);
                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:

using System.IO;

namespace Exercise07
{
    public class Program
    {
        public static int Main(string[] args)
        {
            FileInfo flePeople = new FileInfo("People.txt");
            StreamWriter stwPeople = flePeople.CreateText();

            try
            {
                stwPeople.WriteLine("Stephanie Grizzard");
                stwPeople.WriteLine("Michael Lightgrow");
                stwPeople.WriteLine("Bernadette Herwing");
                stwPeople.WriteLine("Leonard Curtin");
            }
            finally
            {
                stwPeople.Close();
            }

            return 903;
        }
    }
}

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.IO;
using static System.Console;

public class Program
{
    static void SaveFile()
    {
        FileInfo flePeople = new FileInfo("Contractor.txt");

        using (StreamWriter stwPeople = flePeople.CreateText())
        {
            stwPeople.WriteLine("Jeffrey Fahey");
            stwPeople.WriteLine("Denise Haughton");
            stwPeople.WriteLine("Joshua Holliday");
            stwPeople.WriteLine("Virginia Bottoms");
        }
    }

    static void OpenFile()
    {
        string Filename = "Contractor.txt";
        FileInfo flePeople = new FileInfo(Filename);

        using(StreamReader strPeople = flePeople.OpenText())
        {
            WriteLine(strPeople.ReadLine());
            WriteLine(strPeople.ReadLine());
            WriteLine(strPeople.ReadLine());
            WriteLine(strPeople.ReadLine());
        }
    }

    public static int Main()
    {
        SaveFile();

        return 904;
    }
}

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 static System.Console;

public class Program
{
    static private void SaveFile()
    {
        FileInfo flePeople = new FileInfo("People.txt");

        using(StreamWriter stwPeople = flePeople.CreateText())
        {
            stwPeople.WriteLine("Amanda Robinson");
            stwPeople.WriteLine("Rudulph Greens");
            stwPeople.WriteLine("Laura Devine");
            stwPeople.WriteLine("Josh Almas");
        }
    }

    private static void OpenFile()
    {
        string Filename = "People.txt";
        FileInfo flePeople = new FileInfo(Filename);

        if (flePeople.Exists == true)
        {
            using(StreamReader strPeople = flePeople.OpenText())
            {
                WriteLine(strPeople.ReadLine());
                WriteLine(strPeople.ReadLine());
                WriteLine(strPeople.ReadLine());
                WriteLine(strPeople.ReadLine());
            }
        }
        else
            WriteLine("There is no file named People.txt in the indicated location");
    }

    public static int Main()
    {
        SaveFile();

        return 904;
    }
}

Since the default value of an if conditional statement is true, you can omit the == true expression

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:

using System.IO;

public class Program
{
    public static int Main()
    {
    	// 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.


Previous Copyright © 2008-2021, FunctionX Tuesday 19 October 2021 Next