.NET Framework Documentation

IOException Class

System.IO

Represents errors that occur during an I/O operation.

Inheritance

Base Type Object
Derived Types FileAlreadyExistsException, FileNotFoundException, PathTooLongException, etc.
Implemented Interfaces ISerializable

Syntax

[SerializableAttribute]
public class IOException : SystemException

Constructors

Name Description
IOException()
Initializes a new instance of the IOException class.
IOException(string message)
Initializes a new instance of the IOException class with a specified error message.
IOException(string message, Exception innerException)
Initializes a new instance of the IOException class with a specified error message and a reference to the inner exception that is the cause of the current exception.
IOException(string message, int hResult)
Initializes a new instance of the IOException class with a specified error message and HRESULT.

Properties

Name Description
Message Gets an error message that explains the reason for the exception.
InnerException Gets the exception that is the cause of the current exception.
StackTrace Gets a string representing the immediate frame of a call stack.
HelpLink Gets or sets a link to the help file associated with this exception.
HResult Gets or sets the numeric error code assigned to the exception.
Source Gets or sets the name of the application or the object that causes the error.

Methods

Name Description
ToString() Overrides Exception.ToString() to include information about the IO error.
GetObjectData(SerializationInfo info, StreamingContext context) Sets the SerializationInfo object with information about the exception.

Remarks

The IOException class is the base class for exceptions thrown by the System.IO namespace. It provides a general way to handle file and stream-related errors. Many specific exceptions derive from IOException, such as FileNotFoundException, DirectoryNotFoundException, FileLoadException, and PathTooLongException. When you catch an IOException, you can examine its properties to determine the specific cause of the error.

Example

The following code example demonstrates how to catch an IOException when attempting to read from a file that does not exist.

using System;
using System.IO;

public class Example
{
    public static void Main(string[] args)
    {
        string filePath = "nonexistent_file.txt";

        try
        {
            using (StreamReader sr = new StreamReader(filePath))
            {
                string line = sr.ReadToEnd();
                Console.WriteLine(line);
            }
        }
        catch (IOException ex)
        {
            Console.WriteLine($"An IO error occurred: {ex.Message}");
            Console.WriteLine($"Error Code: {ex.HResult}");
            // Further exception handling based on specific types if needed
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An unexpected error occurred: {ex.Message}");
        }
    }
}

See Also