Claus Appel
Claus Appel

Reputation: 1575

Why does JsonConfigurationSource throw FileNotFoundException when file clearly ought to exist?

Consider the following C# code:

var json = "{ \"LogLevel\": \"Debug\" }";
const string filePath = @"C:\temp\tempconfiguration.json";
File.WriteAllText(filePath, json);
var jsonConfigurationSource = new JsonConfigurationSource { Path = filePath };
var jsonConfigurationProvider = new JsonConfigurationProvider(jsonConfigurationSource);
var configuration = new ConfigurationRoot(new List<IConfigurationProvider> { jsonConfigurationProvider });

When I run this, it throws:

System.IO.FileNotFoundException
The configuration file 'C:\temp\tempconfiguration.json' was not found and is not optional.

That makes no sense to me. The file clearly exists (I can see it in Windows Explorer). Can anyone explain to me what goes on here? Thanks in advance!

(I know I can also use JsonStreamConfigurationProvider to read from a stream, but I want to be able to also read the configuration from a file. Mainly because JsonStreamConfigurationProvider does not support IConfigurationRoot.Reload.)

I am running .NET 5.0 and C# 9.

Upvotes: 2

Views: 486

Answers (1)

Evk
Evk

Reputation: 101613

Problem is that Path is relative to FileProvider of JsonConfigurationSource. You can either set FileProvider explicitly:

var jsonConfigurationSource = new JsonConfigurationSource { Path = Path.GetFileName(filePath) };
jsonConfigurationSource.FileProvider = new PhysicalFileProvider(Path.GetDirectoryName(filePath));

Or easier way, call ResolveFileProvider:

var jsonConfigurationSource = new JsonConfigurationSource { Path = filePath };
jsonConfigurationSource.ResolveFileProvider();

Which will automatically create FileProvider from your absolute path AND make that path relative after that (so will do the same as above for you).

Upvotes: 5

Related Questions