MC9*_*000 2 c# console-application appsettings .net-core
Trying to convert Dotnet Core 3.1 to Dotnet6 CONSOLE applications and keep getting
"The configuration file 'appsettings.json' was not found and is not optional. The expected physical path was 'C:\Windows\system32\appsettings.json'."
error message. The thing is, the appsettings.json file IS copied to the publish folder, but I get the error in the Application log and nothing happens.
There are other posts here, but I can't find one specific to DotNet6 (they got rid of startup.cs and are doing things radically different) AND specific to console applications.
I have the appsettings.json Build Action set to Content (or nothing) and set to Copy To Output Directory to Copy Always. The file is absolutely present in the publish folder (and on the server it's running on).
static async Task Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory()) //doesn't work on publish (appsettings.json set to "copy always" - no joy) - thing is that is DOES copy it over, but the program can't find it!
.AddJsonFile("appsettings.json")
.Build();
Run Code Online (Sandbox Code Playgroud)
我假设 .SetBasePath 部分与此处的其他解决方案一样不正确,但无法将 dotnet5 解决方案应用于此问题。我知道我做错了什么,但找不到 DotNet6 控制台应用程序配置的解决方案。有些人建议在 DotNet5 中创建项目,然后转换为 DotNet6,但这确实不能解决问题(太老套),我也没有学习新的/正确的配置方法。有任何想法吗?
好的 - 现在找到了一种可行的方法。看起来仍然像一个拼凑,但它有效,我很高兴......现在。
var configuration = new ConfigurationBuilder()
.SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location))
.AddJsonFile("appsettings.json")
.Build();
Run Code Online (Sandbox Code Playgroud)
当然,有一个内置函数可以实现此目的,但我似乎找不到发布后即可使用的示例。
********** 更新 *********************
这很完美:
var configuration = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json")
.Build();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3098 次 |
| 最近记录: |