ZetCode

C# FileNotFoundException

last modified November 6, 2026

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

FileNotFoundException from the System.IO namespace is thrown when code tries to open a file that does not exist. It derives from IOException. If the directory of the file is missing too, .NET throws a DirectoryNotFoundException instead. The runtime also uses FileNotFoundException when it cannot find an assembly to load.

Methods that only check or remove a file, such as File.Exists, FileInfo.Exists, and File.Delete, do not throw the exception.

Basic example

The first example reads a file that does not exist.

Program.cs
try
{
    string content = File.ReadAllText("missing.txt");
    Console.WriteLine(content);
}
catch (FileNotFoundException e)
{
    string cwd = Environment.CurrentDirectory;

    Console.WriteLine($"Message: {e.Message.Replace(cwd, ".")}");
    Console.WriteLine($"FileName: {e.FileName?.Replace(cwd, ".")}");
    Console.WriteLine($"HResult: 0x{e.HResult:X8}");
    Console.WriteLine($"Base type: {e.GetType().BaseType}");
}

We catch the exception and print its properties.

Console.WriteLine($"FileName: {e.FileName?.Replace(cwd, ".")}");

The FileName property holds the full path of the missing file. The relative name missing.txt was resolved against the working directory. We replace the working directory with a dot to shorten the output.

Console.WriteLine($"HResult: 0x{e.HResult:X8}");

The HResult code is the same on all systems; 0x80070002 is the Windows error code for a missing file.

$ dotnet run
Message: Could not find file './missing.txt'.
FileName: ./missing.txt
HResult: 0x80070002
Base type: System.IO.IOException

Relative paths and the working directory

A common cause of the exception is a relative path. A relative path is resolved against the working directory of the process, which depends on how the program was started, not on where the program or the file is.

Program.cs
Directory.CreateDirectory("demo");
File.WriteAllText(Path.Combine("demo", "settings.txt"), "color=blue");

string start = Environment.CurrentDirectory;

Directory.SetCurrentDirectory("demo");
Load("settings.txt");

Directory.SetCurrentDirectory(start);
Load("settings.txt");

Load(Path.Combine(start, "demo", "settings.txt"));

Directory.Delete("demo", true);

void Load(string path)
{
    string dir = Path.GetRelativePath(start, Environment.CurrentDirectory);

    try
    {
        Console.WriteLine($"[{dir}] {path.Replace(start, ".")}: {File.ReadAllText(path)}");
    }
    catch (FileNotFoundException e)
    {
        Console.WriteLine($"[{dir}] {path}: not found, looked for {e.FileName!.Replace(start, ".")}");
    }
}

We create demo/settings.txt and read settings.txt from two working directories.

Directory.SetCurrentDirectory("demo");
Load("settings.txt");

With demo as the working directory, the relative path finds the file.

Directory.SetCurrentDirectory(start);
Load("settings.txt");

Back in the original directory, the same path points elsewhere and the read fails. The FileName property shows where .NET looked, which is the first thing to check when the exception is unexpected.

For files shipped with the program, build the path from AppContext.BaseDirectory, the directory of the application. For user data, use a directory from Environment.GetFolderPath.

$ dotnet run
[demo] settings.txt: color=blue
[.] settings.txt: not found, looked for ./settings.txt
[.] ./demo/settings.txt: color=blue

A TryRead helper

When a missing file is a normal case, a helper method can turn the exception into a return value.

Program.cs
Directory.CreateDirectory("demo");
File.WriteAllText(Path.Combine("demo", "a.txt"), "alpha");
File.WriteAllText(Path.Combine("demo", "c.txt"), "gamma");

foreach (string name in new[] { "a.txt", "b.txt", "c.txt" })
{
    string? text = TryReadText(Path.Combine("demo", name));
    Console.WriteLine(text is null ? $"{name}: missing, skipped" : $"{name}: {text}");
}

Directory.Delete("demo", true);

static string? TryReadText(string path)
{
    try
    {
        return File.ReadAllText(path);
    }
    catch (FileNotFoundException)
    {
        return null;
    }
}

We read three files, one of which is missing.

static string? TryReadText(string path)

The method returns null for a missing file. Other errors, such as missing permissions, still propagate as exceptions.

Calling File.Exists before reading would also work in a simple program, but the file can be deleted between the check and the read, so the read must handle the exception anyway.

$ dotnet run
a.txt: alpha
b.txt: missing, skipped
c.txt: gamma

Throwing the exception

Our own code can throw FileNotFoundException when a required file is missing, with a message that tells the user what to do.

Program.cs
try
{
    LoadConfig("appsettings.json");
}
catch (FileNotFoundException e)
{
    Console.WriteLine(e.Message);
    Console.WriteLine($"FileName: {e.FileName}");
}

var plain = new FileNotFoundException(null, "data.csv");
Console.WriteLine(plain.Message);

static string LoadConfig(string path)
{
    if (!File.Exists(path))
    {
        throw new FileNotFoundException(
            $"Configuration file '{path}' not found. Copy appsettings.example.json to create it.",
            path);
    }

    return File.ReadAllText(path);
}

The LoadConfig method throws the exception with a message and the file name.

throw new FileNotFoundException(
    $"Configuration file '{path}' not found. Copy appsettings.example.json to create it.",
    path);

The second argument sets the FileName property, which lets the caller read the path without parsing the message.

var plain = new FileNotFoundException(null, "data.csv");

Without a message, the exception uses a default text that talks about loading an assembly, which is confusing for a data file. Always pass a message.

$ dotnet run
Configuration file 'appsettings.json' not found. Copy appsettings.example.json to create it.
FileName: appsettings.json
Could not load file or assembly 'data.csv'. The system cannot find the file specified.

Searching several locations

A program can look for a file in several places, for example a user directory, the working directory, and a directory with defaults.

Program.cs
Directory.CreateDirectory(Path.Combine("demo", "defaults"));
File.WriteAllText(Path.Combine("demo", "defaults", "theme.txt"), "dark");

string[] locations =
[
    Path.Combine("demo", "user", "theme.txt"),
    Path.Combine("demo", "theme.txt"),
    Path.Combine("demo", "defaults", "theme.txt"),
];

try
{
    var (path, text) = ReadFirst(locations);
    Console.WriteLine($"{text} (from {path})");

    ReadFirst(locations[..2]);
}
catch (FileNotFoundException e)
{
    Console.WriteLine(e.Message);
}

Directory.Delete("demo", true);

static (string Path, string Text) ReadFirst(string[] paths)
{
    foreach (string path in paths)
    {
        try
        {
            return (path, File.ReadAllText(path));
        }
        catch (Exception e) when (e is FileNotFoundException or DirectoryNotFoundException)
        {
        }
    }

    throw new FileNotFoundException($"none of these files exist: {string.Join(", ", paths)}");
}

The ReadFirst method returns the first file that can be read.

catch (Exception e) when (e is FileNotFoundException or DirectoryNotFoundException)
{
}

The first location is in a missing directory, so it throws DirectoryNotFoundException. The exception filter skips both kinds of missing paths.

throw new FileNotFoundException($"none of these files exist: {string.Join(", ", paths)}");

If no location has the file, we throw one exception that lists all the paths we tried. The second call, with only the first two locations, shows this case.

$ dotnet run
dark (from demo/defaults/theme.txt)
none of these files exist: demo/user/theme.txt, demo/theme.txt

Missing assemblies

The runtime throws FileNotFoundException when an assembly cannot be found, for example when loading a plugin or when a dependency is missing from the application directory.

Program.cs
using System.Reflection;

try
{
    Assembly.Load("Contoso.Plugins");
}
catch (FileNotFoundException e)
{
    Console.WriteLine(e.Message);
    Console.WriteLine($"FileName: {e.FileName}");
}

We try to load an assembly that does not exist.

Assembly.Load("Contoso.Plugins");

For assemblies, FileName holds the assembly name, not a path. When a deployed application fails with this message, a referenced library is usually missing from the output or publish directory.

$ dotnet run
Could not load file or assembly 'Contoso.Plugins, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.

FileName: Contoso.Plugins, Culture=neutral, PublicKeyToken=null

Source

FileNotFoundException class

In this article we have handled the FileNotFoundException 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.