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 Folder Exists

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

Directory Class

The Directory class is a standard class within the System.IO namespace. It provides a set of static methods that allow the creation, modification and enumeration of folders and sub-folders on a disk or other storage medium. The class contains a method named Exists that allows you to determine whether a named directory exists.

Exists Method

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

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

The following sample code shows a check for the existence of a folder named "C:\windows". Try the test for this folder and others to see the different results. Ensure that the code file includes a using System.IO; statement so that the Directory class is correctly identified.

bool folderExists = Directory.Exists(@"c:\windows");

Exception Detection Considerations

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

14 December 2007