JsonConfigurationSource为何在文件存在时抛出FileNotFoundException异常
.NET 5.0下JsonConfigurationProvider提示配置文件不存在的异常原因
异常核心原因
JsonConfigurationSource的Path属性默认为相对路径,必须配合FileProvider的根路径解析后才是最终查找的文件路径。你未显式指定FileProvider时,组件会默认以当前程序运行的基目录作为根路径,将你传入的C:\temp\tempconfiguration.json绝对路径当作相对路径拼接在基目录后,最终生成的实际查找路径为{程序运行目录}\C:\temp\tempconfiguration.json这类无效路径,因此抛出文件不存在异常。- 次要排查方向:运行.NET程序的用户身份,对目标文件或
C:\temp目录没有读取权限时,操作系统层面的拒绝访问也会被包装为FileNotFoundException抛出。
修复方案
方案1:手动构造Provider时补充FileProvider配置
显式指定物理文件提供器指向配置文件所在的目录即可正确解析路径:
var json = "{ \"LogLevel\": \"Debug\" }"; const string filePath = @"C:\temp\tempconfiguration.json"; File.WriteAllText(filePath, json); var jsonConfigurationSource = new JsonConfigurationSource { Path = Path.GetFileName(filePath), FileProvider = new PhysicalFileProvider(Path.GetDirectoryName(filePath)), ReloadOnChange = true // 按需开启自动重载 }; var jsonConfigurationProvider = new JsonConfigurationProvider(jsonConfigurationSource); var configuration = new ConfigurationRoot(new List<IConfigurationProvider> { jsonConfigurationProvider });
方案2:使用官方扩展方法简化配置(更推荐)
ConfigurationBuilder的AddJsonFile扩展方法内部会自动处理绝对路径解析、FileProvider配置,无需手动处理底层逻辑:
var json = "{ \"LogLevel\": \"Debug\" }"; const string filePath = @"C:\temp\tempconfiguration.json"; File.WriteAllText(filePath, json); var configuration = new ConfigurationBuilder() .AddJsonFile(filePath, optional: false, reloadOnChange: true) .Build();
内容的提问来源于stack exchange,提问作者Claus Appel
相关产品推荐
相关产品推荐

