DirectoryNotFoundException Class
Represents the errors that occur when a path that is not valid is returned from the operating system.
Inheritance
System.Object
System.Exception
System.SystemException
System.IO.IOException
System.IO.DirectoryNotFoundException
Summary
This exception is thrown when the system cannot find a directory, or a part of the specified path is invalid. This can happen for various reasons, including typos in the path, attempting to access a non-existent directory, or permissions issues that prevent the directory from being found.
Syntax
public class DirectoryNotFoundException : IOException
Constructors
DirectoryNotFoundException()
Initializes a new instance of the DirectoryNotFoundException
class.
DirectoryNotFoundException(string message)
Initializes a new instance of the DirectoryNotFoundException
class with a specified error message.
public DirectoryNotFoundException(string message)
message
: The error message that explains the reason for the exception.
DirectoryNotFoundException(string message, Exception innerException)
Initializes a new instance of the DirectoryNotFoundException
class with a specified error message and a reference to the inner exception that is the cause of this exception.
public DirectoryNotFoundException(string message, Exception innerException)
message
: The error message that explains the reason for the exception.innerException
: The exception that is the cause of the current exception. IfinnerException
is notnull
, the last exception thrown in acatch
block that detects the exception is assigned to theInnerException
property.
Remarks
The DirectoryNotFoundException
is typically thrown by methods that operate on directories, such as Directory.GetFiles
or Directory.Delete
, when the specified directory path is invalid or does not exist.
When an exception is thrown as a result of a run-time error, the Exception
object is thrown with the DirectoryNotFoundException
value. The DirectoryNotFoundException
class provides information about the error.
Example
using System;
using System.IO;
public class Example
{
public static void Main(string[] args)
{
string nonExistentDirectory = "C:\\This\\Path\\Does\\Not\\Exist";
try
{
// Attempt to list files in a non-existent directory
string[] files = Directory.GetFiles(nonExistentDirectory);
Console.WriteLine("Files found: {0}", files.Length);
}
catch (DirectoryNotFoundException ex)
{
Console.WriteLine("Error: {0}", ex.Message);
Console.WriteLine("The directory '{0}' was not found.", nonExistentDirectory);
}
catch (Exception ex)
{
Console.WriteLine("An unexpected error occurred: {0}", ex.Message);
}
}
}