System.IO.FileNotFoundException

The exception that is thrown when an attempt to access a file that does not exist on disk fails.

Minimum version: >= 1.1 >= Core 2.0

Statistics

4
elmah.io logo 13

How to handle it

try
{

}
catch (System.IO.FileNotFoundException e)
{

}
try
{

}
catch (System.IO.FileNotFoundException e) when (e.Message.Contains("something"))
{

}
try
{

}
catch (System.IO.FileNotFoundException e) when (LogException(e))
{

}

private static bool LogException(Exception e)
{
    logger.LogError(...);
    return false;
}

How to avoid it

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

Links

YouTube videos

Possible fixes from StackOverflow

Believe it or not, this is normal behaviour. An exception is thrown but handled by the XmlSerializer, so if you just ignore it everything should continue on fine.

I have found this very annoying, and there have been many complaints about this if you search around a bit, but from what I've read Microsoft don't plan on doing anything about it.

You can avoid getting Exception popups all the time while debugging if you switch off first chance exceptions for that specific exception. In Visual Studio, go to Debug -> Exceptions (or press Ctrl + Alt + E), Common Language Runtime Exceptions -> System.IO -> System.IO.FileNotFoundException.

You can find information about another way around it in the blog post C# XmlSerializer FileNotFound exception (which discusses Chris Sells' tool XmlSerializerPreCompiler).

In My case, the file appsettings.json existed in the project folder, but it was set to Do not copy, I changed the setting to Copy always (see images below). And it worked for me.

It will automatically add the following XML to your project.csproj file:

<ItemGroup>
    <Content Update="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
</ItemGroup>

I have looked at other answers, project.json is dead as this answer says.

enter image description here

enter image description here

Update:

From @bunjeeb in comments. Use System.AppContext.BaseDirectory instead of Assembly.GetEntryAssembly().Location for .NET 5 <= with <PublishSingleFile>true</PublishSingleFile>.

Original:

For me the error was using Directory.GetCurrentDirectory(). This worked fine running locally but on a production server it failed when the program was started from Powershell. Replaced with Assembly.GetEntryAssembly().Location and everything worked.

Complete code:

var builder = new ConfigurationBuilder()
        .SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location))
        .AddJsonFile("appsettings.json");

var configuration = builder.Build();

I solved this problem by adding Newtonsoft.Json to the NuGet of the startup project (even though it is not directly used in the startup project).

The OP doesn't include any of the stack trace as part of the exception, but in my case there was a reference in the call stack to my version of the DbContext class.

In the constructor I check the environment to see if we're running on Live. This is because I don't want to throw exceptions if the migrations aren't up to date.

However, in order to do this check it looks up a custom section of the web.config. And, during run time this code creates an "instance" of this custom section, so that the environment can be referred to in various areas of the code.

I don't know whether it's the custom section of the web.config or the way the static "instance" is created in my code, but it seems that this is the root of my exception.

Wrapping it in a #if !DEBUG statement ensures that the PackageManager doesn't trigger this code (which is unnecessary anyway) and I no longer get the exception.

enter image description here

My recommendation would be to strip back your DbContext. If you are using a custom constructor, empty it and test whether it works.