Blog |

How to Handle the FileNotFoundException in C#

How to Handle the FileNotFoundException in C#
Table of Contents

One of the most commonly occurring errors in C#, FileNotFoundException is raised when the developer tries to access a file in the program that either doesn't exist or has been deleted. The following are some of the reasons the system is unable to locate the file:

  • There might be a mismatch in the file name. For instance, instead of "demo.txt", the developer has written "Demo.txt".
  • The file location may have changed.
  • The file might have been deleted.
  • The location or path the developer has passed might be wrong.

 

Syntax of FileNotFoundException

Similar to any class or a method, exceptions also have their own syntax.

Below is the syntax for FileNotFoundException:

public class FileNotFoundException :System.IO.IOException

The FileNotFoundException comes under the class of IOExceptions, which is inherited from the SystemException. SystemException, which is inherited from the Exception class, which is in turn inherited from the Object class.

Object -> Exception -> SystemException -> IOException -> FileNotFoundException

 

An Example of FileNotFoundException

In the below code, System.IO is imported, which is necessary for doing input and output operations on a file. Then within the main method, a try-catch block is placed to catch the exceptions, and within the try block we have our StreamReader class object.

The StreamReader class is used to read text files. An object of StreamReader, the path of file "demo.txt" is passed. This file doesn't exist in its constructor. Then the ReadToEnd method is used to read the file till the end if it exists.

using System.IO;
using System;
class Program {
  static void Main(string[] args) {
    try {
      using (StreamReader reader = new StreamReader("demo.txt")) {
        reader.ReadToEnd();
      }
    } catch (FileNotFoundException e) {
      Console.WriteLine(e.ToString());
    }
  }
}

 

An Output of FileNotFoundException Example

The output below is obtained on executing the above code. It includes a FileNotFoundException along with its stack trace, which we can later use for debugging the exception.

System.IO.FileNotFoundException: Could not find file 'C:\ConsoleApp1\ConsoleApp1\bin\Debug\demo.txt'.
File name: 'C:\ConsoleApp1\ConsoleApp1\bin\Debug\demo.txt'
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)
   at System.IO.StreamReader..ctor(String path)
   at ConsoleApp1.Program.Main(String[] args) in C:\ConsoleApp1\ConsoleApp1\Program.cs:line 17

It is essential to handle exceptions when working with files in any programming language.

 

How Does FileNotFoundException Work in C# ?

The FileNotFoundException class implements HRESULT COR_E_FILENOTFOUND, which contains 0x80070002 value. When the code is executed and the file is not found by the system it creates a new instance of FileNotFoundException() along with a string which contains a system defined message for the error.

Types of FileNotFoundException errors:

The Message property of FileNotFoundException class gives the error message that explains the reason for the occurrence of the exception. This helps you to find out what kind of file not found error it is.

1. Could not find file error:

Let’s look at a block of code to observe this error. Instead of using StreamReader, let's directly use the method ReadAllText of the File class to read the text file.

using System.IO;
using System;
class Program {
 static void Main(string[] args) {
             try {
                File.ReadAllText("demo.txt");
            }
            catch (FileNotFoundException e) {
                Console.WriteLine(e.ToString());
            }
       }
}
Output: Could not find file error

In the following output the error message is of the format Could not find file 'filename'. As discussed previously this happens because the developer is trying to load a file that doesn't exist in the file system. The exception message gives a useful description of the error along with the absolute path to the missing file.

System.IO.FileNotFoundException: Could not find file 'C:\ConsoleApp1\ConsoleApp1\bin\Debug\demo.txt'.
File name: 'C:\ConsoleApp1\ConsoleApp1\bin\Debug\demo.txt'

 

2. Exception from HRESULT: 0x80070002

This error generally occurs when the developer tries to load a non-existing Assembly into the system.

using System.IO;
using System;
using System.Reflection;
class Program {
  static void Main(string[] args) {
    try {
      Assembly.LoadFile("C:\\non_existing_dll_file.dll");
    } catch (FileNotFoundException e) {
      Console.WriteLine(e.ToString());
    }
  }
Output of Exception from HRESULT: 0x80070002

In this scenario as well the same FileNotFoundExceptionis raised but the error message is different. Unlike the previous output, the error message from System.Reflection is quite hard to comprehend. Going through a stack trace can help pinpoint that the error is occurring during Assembly.LoadFile.

System.IO.FileNotFoundException: The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
   at System.Reflection.RuntimeAssembly.nLoadFile(String path, Evidence evidence)
   at System.Reflection.Assembly.LoadFile(String path)
   at ConsoleApp1.Program.Main(String[] args) in C:\ConsoleApp1\ConsoleApp1\Program.cs:line 17

Another thing to keep in mind is that neither the filename nor the file path are provided in the message. This is because no name is printed in the output as the Filename attribute on FileNotFoundException is null.

 

How to debug FileNotFoundException

Let’s look at debugging the code, using the stack trace generated in the first example.

System.IO.FileNotFoundException: Could not find file 'C:\ConsoleApp1\ConsoleApp1\bin\Debug\demo.txt'.
File name: 'C:\ConsoleApp1\ConsoleApp1\bin\Debug\demo.txt'
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)
   at System.IO.StreamReader..ctor(String path)
   at ConsoleApp1.Program.Main(String[] args) in C:\ConsoleApp1\ConsoleApp1\Program.cs:line 17

As we scan the stack trace from bottom to top, the StreamReader object we have created to read the file to end with the path of the “demo.txt” file is creating an issue. This happens as the reader.ReadToEnd() is trying to read the file which doesn’t exist. To resolve this create the file using a File class method File.Create() within the catch block.

Code after debugging:

using System.IO;
using System;
class Program {
  static void Main(string[] args) {
    try {
      using(StreamReader reader = new StreamReader("demo.txt")) {
        reader.ReadToEnd();
      }
    } catch (FileNotFoundException e) {
      Console.WriteLine("File doesn't exists so we created the file");
      File.Create(e.FileName);
    }
  }
}

When the above code is executed we get the following output:

File doesn't exists so we created the file

 

How to Avoid FileNotFoundException in C#

Ultimately, it is better to avoid this exception rather than try to analyze or debug it, which could be time-consuming for extensive projects. You should use the File.Exists() method to determine whether or not a file exists before referring to it. This method returns true if the file exists, else it returns false.

Example of File.Exists() method:

using System.IO;
using System;
class Program {
  static void Main(string[] args) {
    if (File.Exists("demos.txt")) {
      using(StreamReader reader = new StreamReader("check.txt")) {
        reader.ReadToEnd();
      }

    } else {
      Console.WriteLine("File doesn't exist please create it");
    }
  }
}

An Output of File.Exists() method:

File doesn't exist please create it

 

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyse, and manage errors in real-time can help you proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing C# errors are easier than ever. Sign Up Today!

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape