Test if directory exists

Jump to: navigation, search

This C# code snippet tests whether a named directory (folder) exists on disk.

using System;
using System.IO;
 
class DirectoryExistence
{
   public static void Main()
   {
   string directoryString = 
      Directory.GetCurrentDirectory() +
      @"\TestDir";
   Directory.CreateDirectory (directoryString);
   if (Directory.Exists (directoryString))
      Console.WriteLine ("Directory \"{0}\" exists", directoryString);
   else
      Console.WriteLine (
         "Directory \"{0}\" does not exist", directoryString);
   Directory.Delete (directoryString);
   if (Directory.Exists (directoryString))
      Console.WriteLine ("Directory \"{0}\" exists", directoryString);
   else
      Console.WriteLine (
         "Directory \"{0}\" does not exist", directoryString);
   }
}
 Test if directory exists (program output)
Directory "C:\Visual Studio\TestDir" exists
Directory "C:\Visual Studio\TestDir" does not exist
C# Online.NET