FileNotFoundException
A FileNotFoundException
is raised when dealing with file IO. This exception is raised when you access a file that must exist for the method to proceed.
This exception normally is encountered in programs that include the System.IO
namespace. It can be caused by a StreamReader
constructor, or many other classes.
StreamReader
will throw a FileNotFoundException
when you try to read a file that does not exist. The following program shows the FileNotFoundException
being raised.
Main
method are wrapped in an exception-handling construct.FileNotFoundException
and searches the catch statements.using System; using System.IO; class Program { static void Main() { try { // Read in nonexistent file. using (StreamReader reader = new StreamReader("not-there.txt")) { reader.ReadToEnd(); } } catch (FileNotFoundException ex) { // Write error. Console.WriteLine(ex); } } }System.IO.FileNotFoundException: Could not find file '...'
FileNotFoundException
The runtime will locate the catch statement specified in the program, and the body of the catch block will be executed.
Here we discuss some ways you can fix this exception. An error message could be printed. If you do not know if the file exists, it is often better use the File.Exists
method.
Exists
method is a static
method that returns a Boolean
value, allowing you to avoid the FileNotFoundException
.This program causes the FileNotFoundException
to be thrown, by trying to use StreamReader
on a nonexistent file. We noted the C# language's exception handling construct in this case.