C# FileNotFoundException

PHPz
Release: 2024-09-03 15:20:57
Original
870 people have browsed it

While dealing with Files Input Output in C#, various exception might rise, but the FileNotFoundException is raised when we attempt to access a file in our program and that file does not exist or is deleted. So, basically, the FileNotFound Exception occurs when we have an address to a file in our system, but when we execute the program, the file we mentioned or passed, is not to be found. There could be multiple reasons for why this file is not found. The file maybe deleted from the location or the file name could have been changed and does not match with the names we mentioned. It is also possible when we pass a wrong address and when it hits the address, there is no file and thus the exception occurs.

Syntax:

Every method, class or exception has its standard syntax.

In case of FileNotFound Exception, the standard syntax is as follows:

public class FileNotFoundException :System.IO.IOException
Copy after login

The FileNotFound Exception is part of IOException, which is inherited from SystemException, going up to Exception and Object class.

How FileNotFoundException work in C#?

  • The FileNotFoundException implements the HRESULT COR_E_FILENOTFOUND, which holds the 0x80070002 value.
  • This FileNotFound Exception usually occurs when dealing with Input Output operations for files.
  • When the code does not find the file, it creates a new instance of FileNotFoundException() along with its message string, which is a system set message for the error.
  • In variety of such constructors, string can be added, context information and error message can be displayed.
  • Additionally, another constructor can provide reference to the inner exception that caused this exception.

Examples of C# FileNotFoundException

Given below are the examples mentioned:

Example #1

Code:

using System;
using System.IO;
class Program {
static void Main() {
try {
using (StreamReaderfilereader = new StreamReader("nofile.txt")) {
filereader.ReadToEnd();
}
}
catch (FileNotFoundException ex) {
Console.WriteLine(ex);
}
}
}
Copy after login

Explanation:

  • We have simply started with the system files. System.IO is an important import file here, as we will be doing operations over file Input and Output. Then we have our class and main method. We have already entered our try catch block in order to catch the exception. We then have our StreamReader class, which is found in system.IO namespace.
  • The StreamReader class is used to read a text file. It is easy to use and provides a good performance. With StreamReader, we have our object that calls the nofile.txt, which as we know does not exist. Then we have ReadToEnd method which will read the file until the end, if it is found. Finally, we have our catch block, which, of course, as we are speaking holds the FileNotFound Exception and when it catches it, it will be printed in output statement in the next line.
  • Upon successful execution of the above code, the output will be an exception, “Could not find file…”.

Output:

C# FileNotFoundException

Example #2

Here we will execute the code similar to above code, but without any try catch block, it will be simple program, where we cannot guess what exactly could go wrong.

Code:

using System.IO;
using System;
class Program {
static void Main() {
using (StreamReaderfilereader = new StreamReader("incorrectfilename.txt")) {
filereader.ReadToEnd();
}
}
}
Copy after login

Explanation:

  • With our second example, the code is almost similar to our first example, but we have specifically not implemented any way to catch the exception. Started with system file, then our class and main method. Then moving ahead to StreamReader, we have our file name passed, which is incorrect and in the next line we attempt to read the file to the end.
  • But we have not tried to catch or identify the exception here, this is a scenario where we believe that the file exist and so we don’t expect any exception. Upon executing, it will print Unhandled Exception and the “System.IO.FileNotFoundException: Could not find file” will be thrown.

Output:

C# FileNotFoundException

And as you can see, unlike our earlier example, this is an unhandled exception and output is as expected.

How to Avoid FileNotFoundException in C#?

Just like any other exception, this FileNotFound Exception can be avoided. Out of the ways that we can use to avoid this exception, File.Exists method is recommended. When we are uncertain if the file we are passing in argument is not available at the source link, it is better to use File.Exists method. File.Exists method is recommended.

Example:

We will use the File.Exists method in program and see how is can be used further.

Code:

using System.IO;
using System;
class Program {
static void Main() {
bool ifexists = File.Exists("incorrectfilename.txt");
Console.WriteLine("\n "+ifexists);
}
}
Copy after login

Explanation:

  • Our code here is ideally in case if we are not sure of the existence of the file that we are about to use. This is simple implementation, we can have such code in loops where it checks for different or alternative files and whichever exists is selected for the operation.
  • We have File.Exists method, where we have passed the file name and are checking if the file exists.
  • Now in the next line, we have print statement, which will print a boolean value, either True or False, based on the existence of file. Our file does not exists, so it must return a false.

Output:

C# FileNotFoundException

Conclusion

To Conclude, the FileNotFound Exception comes from IO system namespace of the object class. FileNotFoundException is responsible for occurring at times when we pass a file or are attempting to execute input or output operations with file but the file does not exists. Other reasons could be, incorrect file name, or incorrect source link. File Exists method can be used to avoid this exception.

The above is the detailed content of C# FileNotFoundException. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!