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.
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.
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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 11, 2021 (edit).