C# FileNotFoundException Tips

Warning

You want to see an example and possible solution to the FileNotFoundException in your program written in the C# language. This exception is raised when you try to access a file that must exist for the method to proceed. It normally is used in programs that include the System.IO namespace.

This C# exception article shows the FileNotFoundException. It shows possible ways to prevent it.

Example

First, many of the methods on the File class in the base class library function without throwing exceptions on missing files. However, the StreamReader class will throw a FileNotFoundException when you try to read a file that does not exists. This can be very useful in some programs. The following program text shows the FileNotFoundException being raised.

File Handling
Program that throws FileNotFoundException [C#]

using System;
using System.IO;

class Program
{
    static void Main()
    {
	try
	{
	    // Read in non-existent file.
	    using (StreamReader reader = new StreamReader("not-there.txt"))
	    {
		reader.ReadToEnd();
	    }
	}
	catch (FileNotFoundException ex)
	{
	    // Write error.
	    Console.WriteLine(ex);
	}
    }
}

Output

System.IO.FileNotFoundException: Could not find file '...'
Using keyword

Using StreamReader statement. The program defines one method, the Main entry point. The contents of the Main method are wrapped in an exception-handling construct. The code contained in the try block is executed, and since the file does not exist, the runtime allocates a new FileNotFoundException instance and searches the catch statements.

Using StreamReader

Catching FileNotFoundException. The runtime will locate the catch statement specified in the program text, and the body of the catch block will be executed. The text "System.IO.FileNotFoundException: Could not find file..." will be written to the screen.

Solution

Programming tip

Here we discuss some ways you can fix this exception. First, if the file is always supposed to be present in your program and will never be deleted in normal runtime, catching the exception as shown above and logging it is acceptable. However, if you do not know if the file exists, it is often better use the File.Exists method. The Exists method is a static method that returns a Boolean value, allowing you to avoid the FileNotFoundException.

File.Exists Method

Summary

The C# programming language

Here we looked at an example program that causes the FileNotFoundException to be thrown, by trying to use StreamReader on a non-existent file. We noted the C# programming language's exception handling construct in this case, and finally discussed the solution shown and also an alternative solution using File.Exists in the base class library and System.IO namespace.

Exception Handling
.NET