Home
C#
FileNotFoundException Example
This page was last reviewed on Dec 11, 2021.
Dot Net Perls
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.
C# type info. 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.
Exception
File
Example. StreamReader will throw a FileNotFoundException when you try to read a file that does not exist. The following program shows the FileNotFoundException being raised.
StreamReader
Detail 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
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 '...'
Catching FileNotFoundException. The runtime will locate the catch statement specified in the program, and the body of the catch block will be executed.
Discussion. 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.
File.Exists
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 11, 2021 (edit).
Home
Changes
© 2007-2024 Sam Allen.