Directory.Exists Method
Determines whether the given path refers to an existing directory on disk.
Namespace: System.IO
Assembly: mscorlib (in mscorlib.dll)
Parameters
- path
- Type: System.String
The path to test.
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory.
Trailing spaces are removed from the end of the path parameter before checking whether the directory exists.
The path parameter is not case-sensitive.
If you do not have at a minimum read-only permission to the directory, the Exists method will return false.
The Exists method returns false if any error occurs while trying to determine if the specified file exists. This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, a failing or missing disk, or if the caller does not have permission to read the file.
The following example takes an array of file or directory names on the command line, determines what kind of name it is, and processes it appropriately.
// For File.Exists, Directory.Exists using System; using System.IO; using System.Collections; public class RecursiveFileProcessor { public static void Main(string[] args) { foreach(string path in args) { if(File.Exists(path)) { // This path is a file ProcessFile(path); } else if(Directory.Exists(path)) { // This path is a directory ProcessDirectory(path); } else { Console.WriteLine("{0} is not a valid file or directory.", path); } } } // Process all files in the directory passed in, recurse on any directories // that are found, and process the files they contain. public static void ProcessDirectory(string targetDirectory) { // Process the list of files found in the directory. string [] fileEntries = Directory.GetFiles(targetDirectory); foreach(string fileName in fileEntries) ProcessFile(fileName); // Recurse into subdirectories of this directory. string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory); foreach(string subdirectory in subdirectoryEntries) ProcessDirectory(subdirectory); } // Insert logic for processing found files here. public static void ProcessFile(string path) { Console.WriteLine("Processed file '{0}'.", path); } }
- FileIOPermission
for reading files. Associated enumeration: FileIOPermissionAccess.Read
Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.