I have two projects in a single solution:
MyLibrary
that contains appsettings.json
+ Settings.cs
MyMobile
that references MyLibrary
.MyLibrary
{
"Settings": {
"Id": 1,
"Message": "Hello World"
}
}
namespace MyLibrary;
public class Settings
{
public const string SECTION = nameof(Settings);
public int Id { get; set; }
public string Message { get; set; } = null!;
}
MyMobile
public partial class App : Application
{
public App(IOptions<Settings> settings)
{
InitializeComponent();
MainPage = new MainPage(settings.Value.Message);
}
}
public partial class MainPage : ContentPage
{
public MainPage(string message)
{
InitializeComponent();
OutputLabel.Text = message;
}
}
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
using var stream = FileSystem.OpenAppPackageFileAsync("appsettings.json").Result;
builder.Configuration.AddJsonStream(stream); // Microsoft.Extensions.Configuration.Json
builder.Services.AddOptions<Settings>().BindConfiguration(Settings.SECTION);// Microsoft.Extensions.Options.ConfigurationExtensions
// others ...
}
appsettings.json
to Resources/raw
with Build Action : MauiAsset
, it works.
appsettings.json
to Resources/raw
with Build Action : MauiAsset
, it does NOT work.System.AggregateException: 'One or more errors occurred. (The system cannot find the file specified. An item cannot be found with the specified name (appsettings.json).)' FileNotFoundException: The system cannot find the file specified.
What am I missing here?
But if I add as link appsettings.json to Resources/raw with Build Action : MauiAsset, it does NOT work.
I created a new project with the code you provided and reproduce your problem. What I found:
The appsettings.json
file's build action in the Class Library is set as None
. When you add it as link and set its build action As MauiAsset
in the Maui project, the source file's build action is still None
.
So you can fix it by the following steps:
appsettings.json
file's build action as MauiAsst
in the class library.appsettings.json
and add it again in the Maui project.In addition, adding the appsettings.json
directly instead of as link is a better choice.
Set by changing csproj file in the class library:
<ItemGroup>
<MauiAsset Include="appsettings.json" />
</ItemGroup>
=====================
The debugging result image: