HomeSearch

C# FileNotFoundException (catch Example)

This C# exception article shows the FileNotFoundException. It shows possible ways to prevent it.
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. It normally is encountered in programs that include the System.IO namespace.ExceptionFile
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.StreamReader

Tip: This can be useful in some programs. The following program shows the FileNotFoundException being raised.

Main: The contents of the Main method are wrapped in an exception-handling construct.

And: The try block is executed. The file does not exist, so the runtime allocates a FileNotFoundException and searches the catch statements.

Try
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 '...'
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.File.Exists Method

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.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls