File not found exception ошибка

I have an assignment for my CS class where it says to read a file with several test scores and asks me to sum and average them. While summing and averaging is easy, I am having problems with the file reading. The instructor said to use this syntax

Scanner scores = new Scanner(new File("scores.dat"));

However, this throws a FileNotFoundException, but I have checked over and over again to see if the file exists in the current folder, and after that, I figured that it had to do something with the permissions. I changed the permissions for read and write for everyone, but it still did not work and it still keeps throwing the error. Does anyone have any idea why this may be occurring?

EDIT: It was actually pointing to a directory up, however, I have fixed that problem. Now file.exists() returns true, but when I try to put it in the Scanner, it throws the FileNotFoundException

Here is all my code

import java.util.Scanner;
import java.io.*;
public class readInt{
        public static void main(String args[]){
                File file = new File("lines.txt");
                System.out.println(file.exists());
                Scanner scan = new Scanner(file);
        }
}

Stephen C's user avatar

Stephen C

699k95 gold badges812 silver badges1216 bronze badges

asked Oct 10, 2013 at 22:58

scrblnrd3's user avatar

8

There are a number situation where a FileNotFoundException may be thrown at runtime.

  1. The named file does not exist. This could be for a number of reasons including:

    • The pathname is simply wrong
    • The pathname looks correct but is actually wrong because it contains non-printing characters (or homoglyphs) that you did not notice
    • The pathname is relative, and it doesn’t resolve correctly relative to the actual current directory of the running application. This typically happens because the application’s current directory is not what you are expecting or assuming.
    • The path to the file is is broken; e.g. a directory name of the path is incorrect, a symbolic link on the path is broken, or there is a permission problem with one of the path components.
  2. The named file is actually a directory.

  3. The named file cannot be opened for reading for some reason.

The good news that, the problem will inevitably be one of the above. It is just a matter of working out which. Here are some things that you can try:

  • Calling file.exists() will tell you if any file system object exists with the given name / pathname.

  • Calling file.isDirectory() will test if it is a directory.

  • Calling file.canRead() will test if it is a readable file.

  • This line will tell you what the current directory is:

      System.out.println(new File(".").getAbsolutePath());
    
  • This line will print out the pathname in a way that makes it easier to spot things like unexpected leading or trailing whitespace:

      System.out.println("The path is '" + path + "'");
    

    Look for unexpected spaces, line breaks, etc in the output.


It turns out that your example code has a compilation error.

I ran your code without taking care of the complaint from Netbeans, only to get the following exception message:

Exception in thread «main» java.lang.RuntimeException: Uncompilable
source code — unreported exception java.io.FileNotFoundException; must
be caught or declared to be thrown

If you change your code to the following, it will fix that problem.

public static void main(String[] args) throws FileNotFoundException {    
    File file = new File("scores.dat");
    System.out.println(file.exists());
    Scanner scan = new Scanner(file);
}

Explanation: the Scanner(File) constructor is declared as throwing the FileNotFoundException exception. (It happens the scanner it cannot open the file.) Now FileNotFoundException is a checked exception. That means that a method in which the exception may be thrown must either catch the exception or declare it in the throws clause. The above fix takes the latter approach.

Vili's user avatar

Vili

1,60916 silver badges40 bronze badges

answered Oct 11, 2013 at 2:12

Terry Li's user avatar

Terry LiTerry Li

16.9k30 gold badges89 silver badges134 bronze badges

3

The code itself is working correctly. The problem is, that the program working path is pointing to other place than you think.

Use this line and see where the path is:

System.out.println(new File(".").getAbsoluteFile());

answered Oct 10, 2013 at 23:03

libik's user avatar

libiklibik

22.3k9 gold badges44 silver badges87 bronze badges

0

Obviously there are a number of possible causes and the previous answers document them well, but here’s how I solved this for in one particular case:

A student of mine had this problem and I nearly tore my hair out trying to figure it out. It turned out that the file didn’t exist, even though it looked like it did. The problem was that Windows 7 was configured to «Hide file extensions for known file types.» This means that if file appears to have the name «data.txt» its actual filename is «data.txt.txt».

Hope this helps others save themselves some hair.

answered May 8, 2015 at 2:18

petehern's user avatar

petehernpetehern

8031 gold badge8 silver badges11 bronze badges

1

I recently found interesting case that produces FileNotFoundExeption when file is obviously exists on the disk.
In my program I read file path from another text file and create File object:

//String path was read from file
System.out.println(path); //file with exactly same visible path exists on disk
File file = new File(path); 
System.out.println(file.exists());  //false
System.out.println(file.canRead());  //false
FileInputStream fis = new FileInputStream(file);  // FileNotFoundExeption 

The cause of the problem was that the path contained invisible \r\n characters at the end.

The fix in my case was:

File file = new File(path.trim()); 

To generalize a bit, the invisible / non-printing characters could have include space or tab characters, and possibly others, and they could have appeared at the beginning of the path, at the end, or embedded in the path. Trim will work in some cases but not all. There are a couple of things that you can help to spot this kind of problem:

  1. Output the pathname with quote characters around it; e.g.

      System.out.println("Check me! '" + path + "'");
    

    and carefully check the output for spaces and line breaks where they shouldn’t be.

  2. Use a Java debugger to carefully examine the pathname string, character by character, looking for characters that shouldn’t be there. (Also check for homoglyph characters!)

Stephen C's user avatar

Stephen C

699k95 gold badges812 silver badges1216 bronze badges

answered Aug 11, 2016 at 7:55

Yuriy N.'s user avatar

Yuriy N.Yuriy N.

4,9542 gold badges39 silver badges31 bronze badges

An easy fix, which worked for me, is moving my files out of src and into the main folder of the project. It’s not the best solution, but depending on the magnitude of the project and your time, it might be just perfect.

answered Oct 21, 2018 at 11:04

Irina Larisa's user avatar

0

Reading and writing from and to a file can be blocked by your OS depending on the file’s permission attributes.

If you are trying to read from the file, then I recommend using File’s setReadable method to set it to true, or, this code for instance:

String arbitrary_path = "C:/Users/Username/Blah.txt";
byte[] data_of_file;
File f = new File(arbitrary_path);
f.setReadable(true);
data_of_file = Files.readAllBytes(f);
f.setReadable(false); // do this if you want to prevent un-knowledgeable 
                      //programmers from accessing your file.

If you are trying to write to the file, then I recommend using File’s setWritable method to set it to true, or, this code for instance:

String arbitrary_path = "C:/Users/Username/Blah.txt";
byte[] data_of_file = { (byte) 0x00, (byte) 0xFF, (byte) 0xEE };
File f = new File(arbitrary_path);
f.setWritable(true);
Files.write(f, byte_array);
f.setWritable(false); // do this if you want to prevent un-knowledgeable 
                      //programmers from changing your file (for security.)

answered Jul 7, 2017 at 12:57

morphytronx's user avatar

Apart from all the other answers mentioned here, you can do one thing which worked for me.

If you are reading the path through Scanner or through command line args, instead of copy pasting the path directly from Windows Explorer just manually type in the path.

It worked for me, hope it helps someone :)

answered May 27, 2017 at 13:59

Alok's user avatar

AlokAlok

981 silver badge6 bronze badges

I had this same error and solved it simply by adding the src directory that is found in Java project structure.

String path = System.getProperty("user.dir") + "\\src\\package_name\\file_name";
File file = new File(path);
Scanner scanner = new Scanner(file);

Notice that System.getProperty(«user.dir») and new File(«.»).getAbsolutePath() return your project root directory path, so you have to add the path to your subdirectories and packages

answered May 11, 2019 at 16:56

lewiscool's user avatar

lewiscoollewiscool

711 silver badge3 bronze badges

2

You’d obviously figure it out after a while but just posting this so that it might help someone. This could also happen when your file path contains any whitespace appended or prepended to it.

answered Jan 3, 2020 at 15:40

Aditya Vikas Devarapalli's user avatar

Use single forward slash and always type the path manually. For example:

FileInputStream fi= new FileInputStream("D:/excelfiles/myxcel.xlsx");

Cray's user avatar

Cray

2,7747 gold badges22 silver badges32 bronze badges

answered Feb 21, 2020 at 5:56

Lefin K.R's user avatar

What worked for me was catching the exception. Without it the compiler complains even if the file exists.

InputStream file = new FileInputStream("filename");

changed to

try{
    InputStream file = new FileInputStream("filename");
    System.out.println(file.available());
}
catch (Exception e){
    System.out.println(e);
}

answered Mar 8, 2021 at 8:31

tejasvi88's user avatar

tejasvi88tejasvi88

6357 silver badges15 bronze badges

This works for me. It also can read files such txt, csv and .in

public class NewReader {

    public void read() throws FileNotFoundException, URISyntaxException {
        File file = new File(Objects.requireNonNull(NewReader.class.getResource("/test.txt")).toURI());
        Scanner sc = new Scanner(file);

        while (sc.hasNext()) {
            String text = sc.next();
            System.out.println(text);

        }
    }
}

the file is located in resource folder generated by maven. If you have other folders nested in, just add it to the file name like «examples/test.txt».

Suraj Rao's user avatar

Suraj Rao

29.4k11 gold badges94 silver badges103 bronze badges

answered Apr 25, 2022 at 11:57

Tom's user avatar

Курс по Python: https://stepik.org/course/100707

На предыдущем занятии я отмечал, что если указать неверный путь к файлу, то возникнет ошибка:

FileNotFoundError

и программа
досрочно прерывается. Это неприятный момент, тем более, что программист наперед
не может знать, в каких условиях будет работать программа и вполне возможна
ситуация, когда ранее доступный файл становится недоступным, например, из-за
случайного его удаления, или изменении имени и т.п. То есть, при работе с
файлами нужно уметь обрабатывать исключение FileNotFoundError, чтобы
программа продолжала работать, даже если файл не будет найден.

Для обработки
подобных ошибок (или, как говорят, исключений) существует специальная группа
операторов:

try / except / finally

о которых мы
подробно будем говорить в части объектно-ориентированного программирования на Python. Но, несмотря
на то, что это выходит за рамки базового курса, я решил показать, как
использовать эти операторы при работе с файлами. Иначе, ваши программы будут
заведомо содержать серьезную уязвимость при обращении к файлам.

Формально,
операторы try / except / finally имеют,
следующий синтаксис (определение):

try:

       
блок операторов

       
критического кода

except
[исключение]:

       
блок операторов

       
обработки исключения

finally:

       
блок операторов

       
всегда исполняемых

       
вне зависимости, от

        возникновения исключения

И в нашем случае
их можно записать, так:

try:
    file = open("my_file.txt", encoding='utf-8')
    s = file.readlines()
    print(s)
    file.close()
except FileNotFoundError:
    print("Невозможно открыть файл")

Смотрите, здесь
функция open() находится
внутри блока try, поэтому, если
возникнет исключение FileNotFoundError, то выполнение программы перейдет в блок
except и отобразится
строка «Невозможно открыть файл». Иначе, мы прочитаем все строки из файла,
отобразим их в консоли и закроем файл.

Однако, и в
такой реализации не все гладко. В момент считывания информации из файла (в
методе readlines()) также может
возникнуть исключение из-за невозможности считывания информации из файла.
Поэтому, совсем надежно можно было бы реализовать эту программу, следующим
образом:

try:
    file = open("my_file.txt", encoding='utf-8')
 
    try:
        s = file.readline()
        print(s)
    finally:
        file.close()
        
except FileNotFoundError:
     print("Невозможно открыть файл")
except: 
    print("Ошибка при работе с файлом")

Мы здесь
прописываем еще один вложенный блок try, который будет учитывать все
возможные исключения и при их возникновении мы обязательно перейдем в блок finally для закрытия
файла. Это важная процедура – любой ранее открытый файл (функцией open()) следует
закрывать, даже при возникновении исключений. И вот такая конструкция try / finally нам гарантирует
его закрытие, что бы ни произошло в момент работы с ним. Но блок try / finally не отлавливает
исключения, поэтому они передаются внешнему блоку try и здесь мы
должны их обработать. Я сделал это через второй блок except, в котором не
указал никакого типа исключений. В результате, он будет реагировать на любые не
обработанные ошибки, то есть, в нашем случае – на любые ошибки, кроме FileNotFoundError.

Менеджер контекста для файлов

Более я не буду
углубляться в работу блоков try / except / finally. Приведенного
материала пока вполне достаточно, а в заключение этого занятия расскажу о
замене блока try / finally так называемым
файловым менеджером контекста, как это принято делать в программах на Python.

Так вот, в языке
Python существует
специальный оператор with, который, можно воспринимать как аналог
конструкции try / finally и в случае
работы с файлами записывается, следующим образом:

try:
    with open("my_file.txt", encoding='utf-8') as file:
        s = file.readlines()
        print( s )
 
except FileNotFoundError:
     print("Невозможно открыть файл")
except:
    print("Ошибка при работе с файлом")

Смотрите, мы
здесь сразу вызываем функцию open(), создается объект file, через который,
затем, вызываем методы для работы с файлом. Причем, все операторы должны быть
записаны внутри менеджера контекста, так как после его завершения файл
закрывается автоматически. Именно поэтому здесь нет необходимости делать это
вручную.

При работе с
менеджером контекста следует иметь в виду, что он не обрабатывает никаких
ошибок (исключений) и все, что происходит, передается вышестоящему блоку try, где они и
обрабатываются. Но в любом случае: произошли ошибки или нет, файл будет
автоматически закрыт. В этом легко убедиться, если добавить блок finally для оператора try, в котором
отобразить флаг закрытия файла:

try:
    with open("my_file.txt", encoding='utf-8') as file:
        s = file.readlines()
        print( s )
 
except FileNotFoundError:
     print("Невозможно открыть файл")
except:
    print("Ошибка при работе с файлом")
finally:
    print(file.closed)

После запуска
программы видим значение True, то есть, файл был закрыт. Даже если
произойдет критическая ошибка, например, вызовем функцию int() для строки s:

то, снова видим
значение True – файл был
закрыт. Вот в этом удобство использования менеджера контекста при работе с
файлами.

На этом мы
завершим наше ознакомительное занятие по обработке файловых ошибок. Пока будет
достаточно запомнить использование операторов try / except / finally при работе с
файлами, а также знать, как открывать файлы через менеджер контекста. На
следующем уроке мы продолжим тему файлов и будем говорить о способах записи
данных.

Курс по Python: https://stepik.org/course/100707

Видео по теме


By Lenin Mishra
in
python


Learn to handle FileNotFound error in Python using try-except block.

FileNotFoundError Exception in Python

FileNotFound Error in Python

The FileNotFoundError Exception in Python is raised when you are trying to access a file or a directory that doesn’t exist.

Example 1

Code/Output

x = open("random_file.txt")

>>> FileNotFoundError: [Errno 2] No such file or directory: 'random_file.txt'

You can deal with such errors by using the FileNotFoundError Exception class.


Example 2

Code

try:
    x = open('random.txt')
except FileNotFoundError as e:
    print(f"FileNotFoundError successfully handled\n"
          f"{e}")

Output

FileNotFoundError successfully handled
[Errno 2] No such file or directory: 'random.txt'

The above code uses f-strings. Check out that article and other string formatting techniques.

Check out other Python Built-in Exception classes in Python.

built-in-exception-classes — Pylenin

A programmer who aims to democratize education in the programming world and help his peers achieve the career of their dreams.

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!

This is the third part in the series named Debugging common .NET exceptions. Today, I want to help you track down and fix a very common and very well-known exception, System.IO.FileNotFoundException. Admitted! In all instances this error is caused by trying to access a file that isn’t there. But, there are actually multiple scenarios that can trigger this exception. You may think you know everything there is to know about this exception, but I bet there is something left for you to learn. At least I did while digging down into the details for this post. Stay tuned to get the full story.

Debugging System.IO.FileNotFoundException - Cause and fix

Types of file not found errors

Let’s dig into the different causes of this error. The Message property on FileNotFoundException gives a hint about what is going on.

Could not find file ‘filename’

As the message says, you are trying to load a file that couldn’t be found. This type of error can be re-created using a single line of code:

try
{
    File.ReadAllText("non-existing.file");
}
catch (FileNotFoundException e)
{
    Console.WriteLine(e.ToString());
}

line 3 is the important one here. I’m trying to load a file that doesn’t exist on the file system (non-existing.file). In the example above, the program will print output to the console looking similar to this:

System.IO.FileNotFoundException: Could not find file 'APP_PATH\bin\Debug\non-existing.file'.
File name: 'APP_PATH\bin\Debug\non-existing.file'
   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.File.InternalReadAllText(String path, Encoding encoding, Boolean checkHost)
   at System.IO.File.ReadAllText(String path)
   at ConsoleApp.Program.Main(String[] args) in APP_PATH\Program.cs:line 19

APP_PATH will be the absolute path to the file that cannot be found. This type of FileNotFoundException actually contains all the information needed to debug the problem. The exception message contains a nice error description, as well as an absolute path to the missing file. If you want to present the user with the path or maybe create the file when not found, there is a nifty property available on FileNotFoundException:

catch (FileNotFoundException e)
{
    File.Create(e.FileName);
}

In the example I simply create the missing file by using the Filename property. I’ve seen code parsing the exception message to get the name of the missing file, which is kind of a downer when the absolute path is available right there on the exception :)

The system cannot find the file specified. (Exception from HRESULT: 0x80070002)

This error is typically thrown when trying to load an assembly that doesn’t exist. The error can be re-created like this:

try
{
    Assembly.LoadFile("c:\\Nonexisting.dll");
}
catch (FileNotFoundException e)
{
    Console.WriteLine(e.ToString());
}

In this scenario, the program still throws a FileNotFoundException. But the exception message is different:

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 ConsoleApp.Program.Main(String[] args) in APP_PATH\Program.cs:line 20

Unlike the error thrown on reading the missing file, messages from the System.Reflection namespace are harder to understand. To find the cause of this error you will need to look through the stack trace, which hints that this is during Assembly.LoadFile. Notice that no filename is present in the exception message and in this case, the Filename property on FileNotFoundException is null.

Could not load file or assembly ‘assembly’ or one of its dependencies. The system cannot find the file specified.

An error similar to the one above is the Could not load file or assembly 'assembly' or one of its dependencies. The system cannot find the file specified. error. This also means that the program is trying to load an assembly that could not be found. The error can be re-created by creating a program that uses another assembly. Build the program, remove the references assembly (the .dll file) from the bin\Debug folder and run the program. In this case, the program fails during startup:

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
   at ConsoleApp.Program.Main(String[] args)

In this example, I’m referencing an assembly named Lib, which doesn’t exist on the disk or in the Global Assembly Cache (GAC).

The typical cause of this error is that the referenced assembly isn’t on the file system. There can be multiple causes of this. To help you debug this, here are some things to check:

  1. If you are deploying using a system like Azure DevOps or Octopus Deploy, make sure all the files from the build output are copied to the destination.
  2. Right-click the referenced assembly in Visual Studio, click Properties and make sure that Copy Local is set to true:

Set Copy Local to True

Access errors when running on IIS

Until now all instances of this error have been a missing file from the disk. I want to round off this post with a quick comment about security. In some cases, the FileNotFoundException can be caused by the user account trying to access the file, and simply don’t have the necessary access. Under optimal circumstances, the framework should throw a System.UnauthorizedAccessException when this happens. But I have seen the issue in the past when hosting websites on IIS. Make sure that the ASP.NET worker process account (or NETWORK SERVICE depending on which user you are using) has access to all files and folders needed to run the application.

To make sure that the app pool user has access:

  1. Right-click the folder containing your web application
  2. Click Properties
  3. Select the Security tab
  4. Click Edit…
  5. Click Add…
  6. Input IIS AppPool\DefaultAppPool in the text area
  7. Click Check Names and verify that the user is resolved
  8. Click OK
  9. Assign Full control to the new user and save

Assign Full control for the new user

Also make sure to read the other posts in this series: Debugging common .NET exception.

elmah.io: Error logging and Uptime Monitoring for your web apps

This blog post is brought to you by elmah.io. elmah.io is error logging, uptime monitoring, deployment tracking, and service heartbeats for your .NET and JavaScript applications. Stop relying on your users to notify you when something is wrong or dig through hundreds of megabytes of log files spread across servers. With elmah.io, we store all of your log messages, notify you through popular channels like email, Slack, and Microsoft Teams, and help you fix errors fast.

elmah.io app banner

See how we can help you monitor your website for crashes
Monitor your website

Понравилась статья? Поделить с друзьями:
  • File has vanished rsync ошибка
  • File crc error ошибка при распаковке
  • Fix price неизвестная ошибка код 504
  • Fivem ошибка подключения
  • Fivem ошибка при запуске