ZetCode

C# IOException

last modified November 6, 2026

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

IOException from the System.IO namespace is the exception thrown when an input or output operation fails. It is the base class of more specific exceptions, such as FileNotFoundException and DirectoryNotFoundException. Errors that have no specific type, such as a file that is in use, a directory that is not empty, or a full disk, are reported as a plain IOException with a message from the operating system.

The examples create a demo directory in the working directory and delete it at the end. The outputs come from Linux.

The exception hierarchy

The first example checks which exception types derive from IOException.

Program.cs
Type[] types =
[
    typeof(FileNotFoundException),
    typeof(DirectoryNotFoundException),
    typeof(DriveNotFoundException),
    typeof(EndOfStreamException),
    typeof(PathTooLongException),
    typeof(FileLoadException),
    typeof(InternalBufferOverflowException),
    typeof(UnauthorizedAccessException),
];

foreach (Type t in types)
{
    Console.WriteLine($"{t.Name,-32} IOException: {typeof(IOException).IsAssignableFrom(t)}");
}

Console.WriteLine($"IOException derives from {typeof(IOException).BaseType}");

IsAssignableFrom tells whether a variable of type IOException can hold an instance of the other type.

typeof(InternalBufferOverflowException),
typeof(UnauthorizedAccessException),

Two types that look like I/O errors are not I/O exceptions. InternalBufferOverflowException, raised by FileSystemWatcher, derives from SystemException. UnauthorizedAccessException, thrown for missing permissions, is not an IOException either, so a single catch (IOException) does not handle permission errors.

$ dotnet run
FileNotFoundException            IOException: True
DirectoryNotFoundException       IOException: True
DriveNotFoundException           IOException: True
EndOfStreamException             IOException: True
PathTooLongException             IOException: True
FileLoadException                IOException: True
InternalBufferOverflowException  IOException: False
UnauthorizedAccessException      IOException: False
IOException derives from System.SystemException

Common I/O errors

The next example triggers several errors and prints the exception type and message.

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

Run("read missing file", () => File.ReadAllText(Path.Combine("demo", "none.txt")));
Run("delete non-empty dir", () => Directory.Delete(Path.Combine("demo", "sub")));
Run("copy over existing", () => File.Copy(Path.Combine("demo", "sub", "a.txt"), Path.Combine("demo", "sub", "a.txt")));
Run("list a file as dir", () => Directory.GetFiles(Path.Combine("demo", "sub", "a.txt")));

Directory.Delete("demo", true);

static void Run(string label, Action action)
{
    try
    {
        action();
        Console.WriteLine($"{label}: ok");
    }
    catch (IOException e)
    {
        Console.WriteLine($"{label}: {e.GetType().Name}");
        Console.WriteLine($"  {e.Message.Replace(Environment.CurrentDirectory, ".")}");
    }
}

The Run method catches IOException, which also catches its derived types.

Run("delete non-empty dir", () => Directory.Delete(Path.Combine("demo", "sub")));
Run("copy over existing", () => File.Copy(Path.Combine("demo", "sub", "a.txt"), Path.Combine("demo", "sub", "a.txt")));

Deleting a directory that contains files without the recursive flag, and copying to a file that exists without the overwrite flag, throw a plain IOException.

Run("list a file as dir", () => Directory.GetFiles(Path.Combine("demo", "sub", "a.txt")));

Using a file as a directory gives a DirectoryNotFoundException. The messages contain absolute paths; we replace the working directory with a dot to shorten them.

$ dotnet run
read missing file: FileNotFoundException
  Could not find file './demo/none.txt'.
delete non-empty dir: IOException
  Directory not empty : './demo/sub'
copy over existing: IOException
  The file './demo/sub/a.txt' already exists.
list a file as dir: DirectoryNotFoundException
  Could not find a part of the path './demo/sub/a.txt'.

Ordering catch blocks

When several kinds of errors need different handling, the catch blocks go from the most specific type to the most general one.

Program.cs
Directory.CreateDirectory("demo");
string readOnly = Path.Combine("demo", "readonly.txt");
File.WriteAllText(readOnly, "data");
File.SetAttributes(readOnly, FileAttributes.ReadOnly);

Run("read missing file", () => File.ReadAllText(Path.Combine("demo", "missing.txt")));
Run("read in missing dir", () => File.ReadAllText(Path.Combine("demo", "nodir", "file.txt")));
Run("write read-only file", () => File.AppendAllText(readOnly, "more"));
Run("read a directory", () => File.ReadAllText("demo"));

File.SetAttributes(readOnly, FileAttributes.Normal);
Directory.Delete("demo", true);

static void Run(string label, Action action)
{
    try
    {
        action();
    }
    catch (FileNotFoundException)
    {
        Console.WriteLine($"{label}: file not found");
    }
    catch (DirectoryNotFoundException)
    {
        Console.WriteLine($"{label}: directory not found");
    }
    catch (IOException e)
    {
        Console.WriteLine($"{label}: other I/O error: {e.GetType().Name}");
    }
    catch (UnauthorizedAccessException)
    {
        Console.WriteLine($"{label}: access denied");
    }
}

We read a missing file, read from a missing directory, write to a read-only file, and read a directory as if it were a file.

catch (FileNotFoundException)
{
    Console.WriteLine($"{label}: file not found");
}
catch (DirectoryNotFoundException)
{
    Console.WriteLine($"{label}: directory not found");
}
catch (IOException e)

The derived types come before IOException. In the opposite order the compiler reports error CS0160, because the later blocks could never run.

catch (UnauthorizedAccessException)

The last two operations fail with UnauthorizedAccessException, which needs its own catch block. Its position relative to the IOException block does not matter, since neither type derives from the other.

$ dotnet run
read missing file: file not found
read in missing dir: directory not found
write read-only file: access denied
read a directory: access denied

The HResult property

A plain IOException can mean many things. The HResult property holds an error code that identifies the cause more precisely than the type.

Program.cs
Directory.CreateDirectory(Path.Combine("demo", "sub"));
string file = Path.Combine("demo", "data.txt");
File.WriteAllText(file, "data");
File.WriteAllText(Path.Combine("demo", "sub", "x.txt"), "x");

Show("missing file", () => File.ReadAllText(Path.Combine("demo", "none.txt")));
Show("missing directory", () => File.ReadAllText(Path.Combine("demo", "no", "none.txt")));
Show("file exists", () => File.Copy(file, file));
Show("directory not empty", () => Directory.Delete(Path.Combine("demo", "sub")));

using (new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.None))
{
    Show("file locked", () => File.ReadAllText(file));
}

Directory.Delete("demo", true);

static void Show(string label, Action action)
{
    try
    {
        action();
    }
    catch (IOException e)
    {
        Console.WriteLine($"{label,-20} 0x{e.HResult:X8} {e.GetType().Name}");
    }
}

We cause five errors and print their codes.

Console.WriteLine($"{label,-20} 0x{e.HResult:X8} {e.GetType().Name}");

The specific exception types have the same codes on all systems; for example, 0x80070002 means a missing file. For a plain IOException, the code differs by platform. On Windows, it is a Win32 error code in the form 0x8007xxxx, such as 0x80070020 for a sharing violation. On Unix, it is the errno value: 0x11 is EEXIST, 0x27 is ENOTEMPTY, and 0x0B is EWOULDBLOCK, returned when the file is locked.

Checking the code makes error handling precise, but the checks must cover each platform the program runs on. Testing the message text, such as e.Message.Contains("not available"), is worse: messages are localized and change between versions.

$ dotnet run
missing file         0x80070002 FileNotFoundException
missing directory    0x80070003 DirectoryNotFoundException
file exists          0x00000011 IOException
directory not empty  0x00000027 IOException
file locked          0x0000000B IOException

Detecting a full disk

A full disk is an error that a program can report clearly, for example by asking the user to free space.

Program.cs
const int ENOSPC = 28;
const int ERROR_DISK_FULL = 0x70;

if (!File.Exists("/dev/full"))
{
    Console.WriteLine("this example needs the Linux /dev/full device");
    return;
}

try
{
    using var fs = new FileStream("/dev/full", FileMode.Open, FileAccess.Write);
    fs.Write(new byte[4096]);
    fs.Flush();
}
catch (IOException e) when (IsDiskFull(e))
{
    Console.WriteLine($"disk full: {e.Message}");
    Console.WriteLine($"HResult: 0x{e.HResult:X8}");
}

static bool IsDiskFull(IOException e)
{
    int code = e.HResult & 0xFFFF;
    return code == ENOSPC || code == ERROR_DISK_FULL;
}

On Linux, the special file /dev/full always reports that the device is full, which lets us test the error without filling a disk.

catch (IOException e) when (IsDiskFull(e))

The exception filter catches only the disk-full case; other I/O errors propagate.

int code = e.HResult & 0xFFFF;
return code == ENOSPC || code == ERROR_DISK_FULL;

The low 16 bits hold the error number: ENOSPC (28) on Unix and ERROR_DISK_FULL (112) on Windows. Masking makes the same check work for the raw errno and for the 0x8007xxxx form.

$ dotnet run
disk full: No space left on device : '/dev/full'
HResult: 0x0000001C

Adding context to errors

A low-level I/O error does not say what the program was trying to do. Library code can wrap it in an exception with a better message and keep the original as the inner exception.

Program.cs
try
{
    LoadSettings(Path.Combine("demo", "settings.ini"));
}
catch (InvalidOperationException e)
{
    Console.WriteLine(e.Message);
    Console.WriteLine($"caused by: {e.InnerException?.GetType().Name}");
}

static string LoadSettings(string path)
{
    try
    {
        return File.ReadAllText(path);
    }
    catch (IOException e)
    {
        throw new InvalidOperationException($"cannot load settings from {path}", e);
    }
}

LoadSettings catches any I/O error and throws a new exception that names the task.

throw new InvalidOperationException($"cannot load settings from {path}", e);

The second constructor argument sets InnerException, so the original type, message, and stack trace are preserved for logging. Here the directory does not exist, so the cause is a DirectoryNotFoundException.

$ dotnet run
cannot load settings from demo/settings.ini
caused by: DirectoryNotFoundException

Source

IOException class

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