This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Input / Output
.NET 1.1+

Checking that a File Exists

A common verification test to be carried out is checking that a specified file exists. This test process can be easily undertaken using the static methods of the File class, which is provided within the .NET framework.

File Class

The File class is a standard class within the System.IO namespace. It provides a set of static methods that assist with file processing such as copying, moving, renaming and deleting files. The class also contains a method called Exists that allows you to determine whether a named file exists on any disk or network storage directory.

Exists Method

The static Exists method is called with a single string parameter. The parameter contains the folder name and the name of the file to be examined. The folder name can be specified in full or can be provided as a path relative to the current working folder. If the file exists and the current user has the correct permissions to see it, the method returns True. If the file does not exist or is not visible to the user, the method returns False.

NB: This method only checks for the existence of files. Another class is used to check for the existence of folders.

The following sample code shows a check for the existence of a file named "C:\test.txt". Try the test with and without this file in the root of your hard disk to see the different results. Ensure that the code file includes a using System.IO; statement so that the File class is correctly identified.

bool fileExists = File.Exists(@"c:\Test.txt");

Exception Detection Considerations

It is important to check that a file exists before performing an operation upon it to avoid an exception. However, you should still perform any actions upon the file within a try / catch / finally block. This avoids problems due to other users modifying or deleting the file in between testing for its existence and working with it.

12 December 2007