C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
This exception is raised when you access a file that must exist for the method to proceed. It normally is encountered in programs that include the System.IO namespace.
Example. First, many of the methods on the File class in the base class library function without throwing exceptions on missing files. However, StreamReader will throw a FileNotFoundException when you try to read a file that does not exist.
Tip: This can be useful in some programs. The following program shows the FileNotFoundException being raised.
C# program that throws FileNotFoundException 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); } } } Output System.IO.FileNotFoundException: Could not find file '...'
The contents of the Main method are wrapped in an exception-handling construct. The code in the try block is executed, and since the file does not exist, the runtime allocates a FileNotFoundException and searches the catch statements.
Catching FileNotFoundException. The runtime will locate the catch statement specified in the program, and the body of the catch block will be executed. The text "System.IO.FileNotFoundException: Could not find file" is written.
Discussion. 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.
Tip: The Exists method is a static method that returns a Boolean value, allowing you to avoid the FileNotFoundException.
Summary. 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. And we discussed File.Exists.