【问题标题】:Why does JsonConfigurationSource throw FileNotFoundException when file clearly ought to exist?当文件明显应该存在时,为什么 JsonConfigurationSource 会抛出 FileNotFoundException?
【发布时间】:2021-11-10 11:16:05
【问题描述】:

考虑以下 C# 代码:

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 });

当我运行它时,它会抛出:

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

这对我来说毫无意义。该文件显然存在(我可以在 Windows 资源管理器中看到它)。谁能向我解释这里发生了什么?提前致谢!

(我知道我也可以使用JsonStreamConfigurationProvider 从流中读取,但我希望也能够从文件中读取配置。主要是因为JsonStreamConfigurationProvider 不支持@ 987654325@.)

我正在运行 .NET 5.0 和 C# 9。

【问题讨论】:

    标签: c# configuration filenotfoundexception


    【解决方案1】:

    问题是Path 相对于JsonConfigurationSourceFileProvider。您可以明确设置FileProvider

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

    或者更简单的方法,拨打ResolveFileProvider:

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

    这将自动从您的绝对路径创建 FileProvider 并在此之后使该路径相对(因此将为您执行与上述相同的操作)。

    【讨论】:

    • 你是对的!多么可怕的 API! (或者至少,多么糟糕的错误消息。)
    猜你喜欢
    • 2016-03-04
    • 1970-01-01
    • 2013-08-10
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多