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:
     
    // IceCream3.cpp : main project file.
    
    #include "stdafx.h"
    
    using namespace System;
    using namespace System::IO;
    
    // This class is used to create and manage an ice scream
    // and to process an order
    public ref class CIceCream sealed
    {
    public: 
        . . . No Change
    
        // This method is used to display a receipt to the user
        void DisplayReceipt()
        {
            . . . No Change
        }
    	
        void SaveOrder()
        {
            String ^ NameOfFile;
    
    	Console::Write(L"Please enter your initials or the "
    	               L"name we will use to remember your order: ");
    	NameOfFile = Console::ReadLine();
    	if( File::Exists(NameOfFile) )
    	{
    	    char Answer;
    
    	    Console::WriteLine(L"The file you entered exists already.");
    	    Console::Write(L"Do you want to replace it(y/n)?" );
    	    Answer = char::Parse(Console::ReadLine());
    
    	    if( Answer == L'y' || Answer == L'Y' )
    		Console::WriteLine(L"The former order with the "
                                       L"same name will be replaced");
    	    else if( Answer == L'n' || Answer == L'N' )
    	    {
    		Console::WriteLine(L"Please enter a name we will "
                                       L"use to remember this order: ");
    		NameOfFile = Console::ReadLine();
    	    }
    	    else
    		Console::WriteLine(L"Invalid Answer - We will close");
    	
    	    return;
    	}
    	else
    	    Console::WriteLine(L"Great");
        }
    
        void OpenOrder()
        {
            String ^ NameOfFile;
    
    	Console::Write(L"Please enter the name you previously "
                               L"gave to remember your order: ");
    	NameOfFile = Console::ReadLine();
    
    	if( File::Exists(NameOfFile) )
    	    Console::WriteLine(L"The file would have been opened");
            else
    	    Console::WriteLine(L"The name you entered is not registered "
    		               L"in our previous orders");
        }
    };
    
    int main(array<System::String ^> ^args)
    {
        char answer = L'n';
        CIceCream ^ ic = gcnew CIceCream();
        ic->ProcessAnOrder();
    
        Console::Write(L"Do you want us to remember this "
                       L"order the next time you come to "
                       L"get your ice scream (y/n)? ");
    	answer = char::Parse(Console::ReadLine());
    
        if( answer == L'y' || answer == L'Y' )
            ic->SaveOrder();
        else
    	Console::WriteLine(L"It was nice serving you."
                               L"\nCome Again!!!\n");
    
        Console::WriteLine();
        return 0;
    }
  2. 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 © 2004-2007 FunctionX, Inc. Next