ZetCode

C# DirectoryNotFoundException

last modified November 6, 2026

In this article we show how to handle the DirectoryNotFoundException in C#.

DirectoryNotFoundException from the System.IO namespace is thrown when a directory, or a part of a file's path, cannot be found. It derives from IOException. Typical causes are a typo in a path, a relative path resolved against an unexpected working directory, a drive or network share that is not available, and a directory that was deleted by another process.

The examples create a demo directory in the working directory where needed; the outputs come from Linux.

Basic example

The first example lists the files of a directory that does not exist.

Program.cs
string path = Path.Combine("demo", "missing");

try
{
    string[] files = Directory.GetFiles(path);
    Console.WriteLine($"found {files.Length} files");
}
catch (DirectoryNotFoundException e)
{
    Console.WriteLine($"directory not found: {e.Message.Replace(Environment.CurrentDirectory, ".")}");
}

Directory.GetFiles throws the exception, which we catch and report.

Console.WriteLine($"directory not found: {e.Message.Replace(Environment.CurrentDirectory, ".")}");

The message contains the absolute path. We replace the working directory with a dot to shorten it. The message says "a part of the path", because any directory in the path may be the missing one.

$ dotnet run
directory not found: Could not find a part of the path './demo/missing'.

Missing file or missing directory

When opening a file, .NET distinguishes between a missing file and a missing directory in its path.

Program.cs
Directory.CreateDirectory("demo");

Try("missing file", () => File.ReadAllText(Path.Combine("demo", "nofile.txt")));
Try("missing directory", () => File.ReadAllText(Path.Combine("demo", "nodir", "file.txt")));

try
{
    File.ReadAllText(Path.Combine("demo", "nodir", "file.txt"));
}
catch (IOException e)
{
    Console.WriteLine($"caught as IOException: {e is DirectoryNotFoundException}");
}

Type? t = typeof(DirectoryNotFoundException);
var chain = new List<string>();

while (t is not null)
{
    chain.Add(t.Name);
    t = t.BaseType;
}

Console.WriteLine(string.Join(" -> ", chain));

Directory.Delete("demo", recursive: true);

static void Try(string label, Action action)
{
    try
    {
        action();
    }
    catch (DirectoryNotFoundException)
    {
        Console.WriteLine($"{label}: DirectoryNotFoundException");
    }
    catch (FileNotFoundException)
    {
        Console.WriteLine($"{label}: FileNotFoundException");
    }
}

We read a missing file from an existing directory and a file from a missing directory, and print the inheritance chain of the exception.

Try("missing file", () => File.ReadAllText(Path.Combine("demo", "nofile.txt")));
Try("missing directory", () => File.ReadAllText(Path.Combine("demo", "nodir", "file.txt")));

The first call throws FileNotFoundException, the second DirectoryNotFoundException. Both derive from IOException.

catch (IOException e)

Catching IOException handles both cases, as well as other I/O errors such as a locked file. When several catch blocks are used, the more specific exceptions must come first.

$ dotnet run
missing file: FileNotFoundException
missing directory: DirectoryNotFoundException
caught as IOException: True
DirectoryNotFoundException -> IOException -> SystemException -> Exception -> Object

Which operations throw

Most methods that read or write a directory throw the exception for a missing path. Methods that only query state do not.

Program.cs
string missing = Path.Combine("demo", "missing");
Directory.CreateDirectory("demo");
File.WriteAllText(Path.Combine("demo", "a.txt"), "a");

Check("Directory.GetFiles", () => Directory.GetFiles(missing));
Check("Directory.EnumerateFiles", () => Directory.EnumerateFiles(missing));
Check("Directory.Delete", () => Directory.Delete(missing));
Check("Directory.Move", () => Directory.Move(missing, Path.Combine("demo", "x")));
Check("Directory.SetCurrentDirectory", () => Directory.SetCurrentDirectory(missing));
Check("File.WriteAllText", () => File.WriteAllText(Path.Combine(missing, "b.txt"), "b"));
Check("File.Copy", () => File.Copy(Path.Combine("demo", "a.txt"), Path.Combine(missing, "a.txt")));
Check("new StreamWriter", () => new StreamWriter(Path.Combine(missing, "c.txt")).Dispose());
Check("new FileSystemWatcher", () => new FileSystemWatcher(missing).Dispose());
Check("Directory.Exists", () => Directory.Exists(missing));
Check("Directory.GetLastWriteTime", () => Directory.GetLastWriteTime(missing));
Check("new DirectoryInfo", () => new DirectoryInfo(missing));

Directory.Delete("demo", recursive: true);

static void Check(string name, Action action)
{
    try
    {
        action();
        Console.WriteLine($"{name,-30} no exception");
    }
    catch (Exception e)
    {
        Console.WriteLine($"{name,-30} {e.GetType().Name}");
    }
}

We call various methods with a missing directory and print the exception type.

Check("Directory.EnumerateFiles", () => Directory.EnumerateFiles(missing));

Although EnumerateFiles is lazy, it checks the directory immediately and throws at the call, not during the enumeration.

Check("Directory.Move", () => Directory.Move(missing, Path.Combine("demo", "x")));

On Linux, moving a missing directory throws a plain IOException, although the documentation lists DirectoryNotFoundException for this case. Catching IOException covers both.

Check("new FileSystemWatcher", () => new FileSystemWatcher(missing).Dispose());

The FileSystemWatcher constructor validates its argument and throws an ArgumentException.

Check("Directory.Exists", () => Directory.Exists(missing));
Check("Directory.GetLastWriteTime", () => Directory.GetLastWriteTime(missing));
Check("new DirectoryInfo", () => new DirectoryInfo(missing));

Exists returns false, the timestamp methods return a default date, and the DirectoryInfo constructor does not access the file system.

$ dotnet run
Directory.GetFiles             DirectoryNotFoundException
Directory.EnumerateFiles       DirectoryNotFoundException
Directory.Delete               DirectoryNotFoundException
Directory.Move                 IOException
Directory.SetCurrentDirectory  DirectoryNotFoundException
File.WriteAllText              DirectoryNotFoundException
File.Copy                      DirectoryNotFoundException
new StreamWriter               DirectoryNotFoundException
new FileSystemWatcher          ArgumentException
Directory.Exists               no exception
Directory.GetLastWriteTime     no exception
new DirectoryInfo              no exception

Creating the directory first

The best way to avoid the exception when writing files is to create the directory before writing.

Program.cs
string filePath = Path.Combine("demo", "reports", "2026", "summary.txt");

try
{
    File.WriteAllText(filePath, "first attempt");
}
catch (DirectoryNotFoundException)
{
    Console.WriteLine("write failed: the directory does not exist");
}

string? dir = Path.GetDirectoryName(filePath);

if (dir is not null)
{
    Directory.CreateDirectory(dir);
}

File.WriteAllText(filePath, "second attempt");
Console.WriteLine($"written: {File.ReadAllText(filePath)}");

Directory.Delete("demo", recursive: true);

The first write fails because the directory tree does not exist. Then we create it and write again.

string? dir = Path.GetDirectoryName(filePath);

Path.GetDirectoryName returns the directory part of a file path. It returns null for a root path.

Directory.CreateDirectory(dir);

CreateDirectory creates all missing directories and does nothing if they exist, so it is safe to call it every time before writing.

$ dotnet run
write failed: the directory does not exist
written: second attempt

DirectoryInfo and missing directories

The properties of a DirectoryInfo object for a missing directory do not throw. They return default values. Methods that access the contents throw.

Program.cs
var di = new DirectoryInfo(Path.Combine("demo", "missing"));

Console.WriteLine($"Exists: {di.Exists}");
Console.WriteLine($"Name: {di.Name}");
Console.WriteLine($"Attributes: {(int)di.Attributes}");
Console.WriteLine($"LastWriteTimeUtc: {di.LastWriteTimeUtc:yyyy-MM-dd}");

try
{
    FileInfo[] files = di.GetFiles();
}
catch (DirectoryNotFoundException e)
{
    Console.WriteLine($"GetFiles: {e.GetType().Name}");
}

try
{
    di.Attributes = FileAttributes.ReadOnly;
}
catch (IOException e)
{
    Console.WriteLine($"setting Attributes: {e.GetType().Name}");
}

We read the properties of a missing directory, list its files, and set its attributes.

Console.WriteLine($"Attributes: {(int)di.Attributes}");
Console.WriteLine($"LastWriteTimeUtc: {di.LastWriteTimeUtc:yyyy-MM-dd}");

The Attributes property returns -1 and the timestamps return January 1, 1601. Check Exists before relying on these values.

di.Attributes = FileAttributes.ReadOnly;

Setting a property, by contrast, modifies the file system and throws the exception.

$ dotnet run
Exists: False
Name: missing
Attributes: -1
LastWriteTimeUtc: 1601-01-01
GetFiles: DirectoryNotFoundException
setting Attributes: DirectoryNotFoundException

Directories that disappear

Checking Directory.Exists before an operation does not guarantee success, because another process can delete the directory between the check and the operation. Code that processes many directories should handle the exception for each directory and continue.

Program.cs
Directory.CreateDirectory(Path.Combine("demo", "a"));
Directory.CreateDirectory(Path.Combine("demo", "b"));
Directory.CreateDirectory(Path.Combine("demo", "c"));

foreach (string d in new[] { "a", "b", "c" })
{
    File.WriteAllText(Path.Combine("demo", d, "file.txt"), d);
}

string[] dirs = Directory.GetDirectories("demo");
Array.Sort(dirs);

Directory.Delete(Path.Combine("demo", "b"), recursive: true);

foreach (string dir in dirs)
{
    try
    {
        int count = Directory.GetFiles(dir).Length;
        Console.WriteLine($"{Path.GetFileName(dir)}: {count} files");
    }
    catch (DirectoryNotFoundException)
    {
        Console.WriteLine($"{Path.GetFileName(dir)}: removed, skipping");
    }
}

if (Directory.Exists(Path.Combine("demo", "a")))
{
    Directory.Delete(Path.Combine("demo", "a"), recursive: true);
}

try
{
    Directory.Delete(Path.Combine("demo", "a"));
}
catch (DirectoryNotFoundException)
{
    Console.WriteLine("a was already deleted");
}

Directory.Delete("demo", recursive: true);

We list three directories, then one of them is deleted before we process the list. This simulates another program removing the directory.

catch (DirectoryNotFoundException)
{
    Console.WriteLine($"{Path.GetFileName(dir)}: removed, skipping");
}

The exception is handled inside the loop, so the other directories are still processed.

try
{
    Directory.Delete(Path.Combine("demo", "a"));
}

Deleting a directory that is already gone throws too. When the goal is only to make sure the directory does not exist, the exception can be ignored.

$ dotnet run
a: 1 files
b: removed, skipping
c: 1 files
a was already deleted

A reusable helper

A helper method can run an operation and, if the directory is missing, create it and try once more.

Program.cs
string path = Path.Combine("demo", "custom", "reports");

int count = WithDirectory(path, p => Directory.GetFiles(p).Length);
Console.WriteLine($"found {count} files");

string file = Path.Combine("demo", "logs", "app.log");
WithDirectory(Path.GetDirectoryName(file)!, _ =>
{
    File.AppendAllText(file, "started\n");
    return true;
});
Console.WriteLine($"log: {File.ReadAllText(file).Trim()}");

Directory.Delete("demo", recursive: true);

static T WithDirectory<T>(string path, Func<string, T> operation)
{
    try
    {
        return operation(path);
    }
    catch (DirectoryNotFoundException)
    {
        Console.WriteLine($"creating {path}");
        Directory.CreateDirectory(path);
        return operation(path);
    }
}

The WithDirectory method wraps a function that works with a directory.

static T WithDirectory<T>(string path, Func<string, T> operation)

The method is generic, so the operation can return any value.

catch (DirectoryNotFoundException)
{
    Console.WriteLine($"creating {path}");
    Directory.CreateDirectory(path);
    return operation(path);
}

The second call is outside the try block. If it fails again, the exception propagates to the caller instead of looping. Creating missing directories automatically is appropriate for output directories, such as logs or reports; for input directories, a missing path usually means a configuration error that should be reported.

$ dotnet run
creating demo/custom/reports
found 0 files
creating demo/logs
log: started

Source

DirectoryNotFoundException class

In this article we have handled the DirectoryNotFoundException in C#.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.