.NET 中的配置问题,读取 json 文件时出现问题

Problem with configuration in .NET,problem with read a json file

当我尝试添加 JSON 文件 via.AddJsonFile() 时,它抛出一个:

System.IO.FileNotFoundException: 'The configuration file 'appsettings.json' was not found and is not optional. The expected physical path was '/data/user/0/com.companyname.rakeshproj/files/appsettings.json'.'

截图:

namespace RakeshProj;
using Microsoft.Extensions.Configuration;
public partial class AppShell : Shell
{
    public AppShell()
    {
        InitializeComponent();
        //Extensions.JsonRead(@"C:\Users\Matsenko\source\repos\TestJson\TestJson\appsettings.json");
        /////////////////Problem
        IConfiguration config = new ConfigurationBuilder()
        //.AddJsonFile("appsettings`.json", optional: true, reloadOnChange: true)
        .AddJsonFile("appsettings.json")
        .AddEnvironmentVariables()
        .Build();
        /////////////////Problem
        //Menu menu_settings = config.GetSection("ShellContentNames").Get<Menu>();


        ShellContent[][] ShellContentName= 
        {
        new ShellContent[3]
        {
            ShellContent1_1,ShellContent2_1,ShellContent3_1
        },
        new ShellContent[13]
        {
                 ShellContent1_2,ShellContent2_2,ShellContent3_2,
                 ShellContent4_2,ShellContent5_2,ShellContent6_2,
                 ShellContent7_2,ShellContent8_2,ShellContent9_2,
                 ShellContent10_2,ShellContent11_2,ShellContent12_2,ShellContent13_2    
        }
        };
        string[][] ShellContentTitle =
        {
        new string[3]
        {
            "Test1_1","Test2_1","Test3_1"
        },
        new string[13]
        {
                 "Test1_2","Test2_2","Test3_2",
                 "Test4_2","Test5_2","Test6_2",
                 "Test7_2","Test8_2","Test9_2",
                 "Test10_2","Test11_2","Test12_2","Test13_2"
        }
        };

        for (int i = 0; i < ShellContentName.Length; i++)
        {
            for(int j=0; j < ShellContentName[i].Length; j++)
            {
                ShellContentName[i][j].Title = ShellContentTitle[i][j];
                SemanticScreenReader.Announce(ShellContentName[i][j].Title);
            }
        }

    }
}

检查文件的属性,它们应该与屏幕截图中的一样:

构建操作:内容

复制到输出目录:如果较新则复制

我想知道这是否与您的配置生成器不知道该文件被 Copy Always 编辑到哪里有关。我喜欢通过将我的配置生成器的基本路径设置为执行或入口点程序集的位置来明确。

从构建器中尝试以下扩展之一:

  • 使用GetExecutingAssembly

    • .SetBasePath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))
  • 使用GetEntryAssembly

    • .SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location))

只有在库或包中构建配置时才真正需要 GetEntryAssembly 版本