Home

The .NET Support for Files

 

Introduction

The primary support of a file as an object is provided by a .NET Framework class called File. This static class is equipped with various types of (static) methods to create, save, open, copy, move, delete, or check the existence of a file.

File Existence

One of the valuable operations that the File class can perform is to check the existence of the file you want to use. For example, if you are creating a new file, you may want to make sure it doesn't exist already because if you try to create a file that exists already, the compiler may first delete the old file before creating the new one.

This could lead to unpredictable result, especially because such a file is not sent to the Recycle Bin. On the other hand, if you are trying to open a file, you should first make sure the file exists, otherwise the compiler will not be able to open a file it cannot find.

To check the existence of a file, the File class provides the Exists method. Its syntax is:

public static bool Exists(string path);

If you provide only the name of the file, the compiler would check it in the folder of the application. If you provide the path to the file, the compiler would check its drive, its folder(s) and the file itself. In both cases, if the file exists, the method returns true. If the compiler cannot find the file, the method returns false. It's important to know that if you provided a complete path to the file, any slight mistake would produce a false result.

Practical LearningPractical Learning: Checking the Existence of a File

  1. Access the IceCream.cs file and change it as follows:
    using System;
    using System.IO;
    
    namespace IceCream3
    {
        delegate void Request();
    
        . . . No Change
            
    
            // This method is used to display a receipt to the user
            public void DisplayReceipt()
            {
                . . . No Change
            }
    
            public void SaveOrder()
            {
                string NameOfFile;
    
                Console.Write("Please enter your initials or the " +
                              "name we will use to remember your order: ");
                NameOfFile = Console.ReadLine();
    			
    	    if( File.Exists(NameOfFile) )
    	    {
    		char Answer;
    
    		Console.WriteLine("The file you entered exists already.");
    		Console.Write("Do you want to replace it(y/n)?" );
    		Answer = char.Parse(Console.ReadLine());
    
    		if( Answer == 'y' || Answer == 'Y' )
    		    Console.WriteLine("The former order with the " +
                                          "same name will be replaced");
    		else if( Answer == 'n' || Answer == 'N' )
    		{
    		    Console.WriteLine("Please enter a name we will " +
                                          "use to remember this order: ");
    		    NameOfFile = Console.ReadLine();
    		}
    		else
    		    Console.WriteLine("Invalid Answer - We will close");
    	
    		    return;
    		}
    		else
    	    	    Console.WriteLine("Great");
            }
    
            public void OpenOrder()
            {
                string NameOfFile;
    
                Console.Write("Please enter the name you previously " +
                              "gave to remember your order: ");
                NameOfFile = Console.ReadLine();
    
                if (File.Exists(NameOfFile))
                    Console.WriteLine("The file would have been opened");
                else
                    Console.WriteLine("The name you entered is not registered " +
                                      "in our previous orders");
            }
        }
    }
  2. Access the Program.cs file and change it as follows:
    using System;
    
    namespace IceCream3
    {
        class Program
        {
            static int Main(string[] args)
            {
                char answer = 'n';
                IceCream ic = new IceCream();
                Request process = new Request(ic.ProcessAnOrder);
    
                process();
    
                Console.Write("Do you want us to remember this " +
                              "order the next time you come to " +
                              "get your Ice Cream (y/n)? ");
                answer = char.Parse(Console.ReadLine());
    
                if (answer == 'y' || answer == 'Y')
                    ic.SaveOrder();
                else
                    Console.WriteLine("\nIt was nice serving you." + 
                                      "\nCome Again!!!\n");
    
                return 0;
            }
        }
    }
  3. Save the file
  4. Compile and execute it

File Creation

Besides checking the existence of the file, the File class can be used to create a new file. To support this operation, the File class is equipped with the Create() method that is overloaded with two versions as follows:

public static FileStream Create(string path);
public static FileStream Create(string path, int buffersize);

In both cases, the File.Create() method returns a Stream value, in this case a FileStream value. As the File.Create() method indicates, it takes the name or path of the file as argument. If you know or want to specify the size, in bytes, of the file, you can use the second version.

To provide the same operation of creating a file, you can use the Open() method of the File class. It is overloaded in three versions as follows:

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

Access to a File

In order to perform an operation on a file, you must specify to the operating system how to proceed. One of the options you have is to indicate the type of access that will be granted on the file. This access is specified using the FileAccess enumerator. The members of the FileAccess enumerator are:

  • FileAccess.Write: New data can be written to the file
  • FileAccess.Read: Existing data can be read from the file
  • FileAccess.ReadWrite: Existing data can be read from the file and new data be written to the file

File Sharing

In standalone workstations, one person is usually able to access and open a file then perform the necessary operations on it. In networked computers, you may create a file that different people can access at the same time or you may make one file access another file to retrieve information. For example, suppose you create an application for a fast food restaurant that has two or more connected workstations and all workstations save their customers orders to a common file. In this case, you must make sure that any of the computers can access the file to save an order. An employee from one of these workstations must also be able to open the file to retrieve a customer order for any necessary reason. You can also create a situation where one file holds an inventory of the items of a store and another file holds the customers orders. Obviously one file would depend on another. Based on this, when an operation must be performed on a file, you may have to specify how a file can be shared. This is done through the FileShare enumerator.

The values of the FileShare enumerator are:

  • FileShare.Inheritable: Allows other file handles to inherit from this file
  • FileShare.None: The file cannot be shared
  • FileShare.Read: The file can be opened and read from
  • FileShare.Write: The file can be opened and written to
  • FileShare.ReadWrite: The file can be opened to write to it or read from it

 

The Mode of a File

Besides the access to the file, another option you will most likely specify to the operating system is referred to as the mode of a file. It is specified through the FileMode enumerator. The members of the FileMode Enumerator are:

  • FileMode.Append: If the file already exists, the new data will be added to its end. If the file doesn't exist, it will be created and the new data will be added to it
  • FileMode.Create: If the file already exists, it will be deleted and a new file with the same name will be created. If the file doesn't exist, then it will be created
  • FileMode.CreateNew: If the new already exists, the compiler will throw an error. If the file doesn't exist, it will be created
  • FileMode.Open: If the file exists, it will be opened. If the file doesn't exist, an error would be thrown
  • FileMode.OpenOrCreate: If the file already exists, it will be opened. If the file doesn't exist, it will be created
  • FileMode.Truncate: If the file already exists, its contents will be deleted completely but the file will be kept, allowing you to write new data to it. If the file doesn't exist, an error would be thrown
 

Previous Copyright © 2006-2016, FunctionX, Inc. Next