Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to capture file not found exception in C#?
The FileNotFoundException is thrown when you try to access a file that does not exist on the system. This commonly occurs when using classes like StreamReader, File.ReadAllText(), or other file I/O operations with an incorrect file path.
Syntax
Following is the syntax for handling FileNotFoundException using try-catch −
try {
// File operation that might throw FileNotFoundException
} catch (FileNotFoundException ex) {
// Handle the exception
Console.WriteLine("File not found: " + ex.Message);
}
Using StreamReader with Exception Handling
When using StreamReader to read a file that doesn't exist, a FileNotFoundException is thrown. Here's how to handle it properly −
using System;
using System.IO;
class Program {
public static void Main() {
try {
using (StreamReader sReader = new StreamReader("new.txt")) {
string content = sReader.ReadToEnd();
Console.WriteLine("File content: " + content);
}
} catch (FileNotFoundException ex) {
Console.WriteLine("File Not Found!");
Console.WriteLine("Error: " + ex.Message);
}
}
}
The output of the above code is −
File Not Found! Error: Could not find file 'C:\path\to\current\directory\new.txt'.
Using File.ReadAllText() with Exception Handling
The File.ReadAllText() method also throws FileNotFoundException when the specified file doesn't exist −
using System;
using System.IO;
class Program {
public static void Main() {
try {
string content = File.ReadAllText("nonexistent.txt");
Console.WriteLine("File content: " + content);
} catch (FileNotFoundException ex) {
Console.WriteLine("The specified file was not found.");
Console.WriteLine("File name: " + ex.FileName);
}
}
}
The output of the above code is −
The specified file was not found. File name: nonexistent.txt
Comprehensive File Exception Handling
In real applications, you should handle multiple types of exceptions that can occur during file operations −
using System;
using System.IO;
class Program {
public static void Main() {
string fileName = "data.txt";
try {
using (StreamReader reader = new StreamReader(fileName)) {
string line;
while ((line = reader.ReadLine()) != null) {
Console.WriteLine(line);
}
}
} catch (FileNotFoundException ex) {
Console.WriteLine($"File '{ex.FileName}' not found.");
} catch (DirectoryNotFoundException ex) {
Console.WriteLine("Directory not found: " + ex.Message);
} catch (UnauthorizedAccessException ex) {
Console.WriteLine("Access denied: " + ex.Message);
} catch (IOException ex) {
Console.WriteLine("I/O error occurred: " + ex.Message);
}
}
}
The output of the above code is −
File 'data.txt' not found.
Checking File Existence Before Access
To prevent FileNotFoundException, you can check if a file exists before attempting to read it −
using System;
using System.IO;
class Program {
public static void Main() {
string fileName = "example.txt";
if (File.Exists(fileName)) {
try {
string content = File.ReadAllText(fileName);
Console.WriteLine("File content: " + content);
} catch (IOException ex) {
Console.WriteLine("Error reading file: " + ex.Message);
}
} else {
Console.WriteLine($"File '{fileName}' does not exist.");
Console.WriteLine("Creating a sample file...");
File.WriteAllText(fileName, "Sample content for demonstration.");
Console.WriteLine("File created successfully.");
}
}
}
The output of the above code is −
File 'example.txt' does not exist. Creating a sample file... File created successfully.
Conclusion
The FileNotFoundException occurs when attempting to access non-existent files. Use try-catch blocks to handle this exception gracefully, and consider checking file existence with File.Exists() before performing file operations to provide better user experience.
