MAUI: What build action for appsettings.json and how to access the file on Android?

Viewed 2510

I created an appsettings file for a MAUI app and loading it in the IConfiguration using .Host.ConfigureAppConfiguration on the builder from a MauiApp.CreateBuilder(); I can access the file in Windows but not when running the Android emulator. The code:

 var builder = MauiApp.CreateBuilder();
            builder
                .RegisterBlazorMauiWebView()
                .UseMauiApp<App>()
                .ConfigureFonts(fonts =>
                {
                    fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                })
                .Host
                .ConfigureAppConfiguration((app, config) =>
                {
#if __ANDROID__
                    // https://stackoverflow.com/questions/49867588/accessing-files-through-a-physical-path-in-xamarin-android
                    //var documentsFolderPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
                    config.AddJsonFile( "appsettings.json", optional: false, reloadOnChange: true);
#endif

#if WINDOWS10_0_17763_0_OR_GREATER
                    //https://stackoverflow.com/questions/69000474/how-to-load-app-configuration-from-appsettings-json-in-maui-startup
                    Assembly callingAssembly = Assembly.GetEntryAssembly();
                    Version versionRuntime = callingAssembly.GetName().Version;
                    string assemblyLocation = Path.GetDirectoryName(System.AppContext.BaseDirectory); //CallingAssembly.Location
                    var configFile = Path.Combine(assemblyLocation, "appsettings.json");
                    config.AddJsonFile(configFile, optional: false, reloadOnChange: true);
#endif
                });

Mockup project is here

3 Answers

There is an open issue Add support for appsetting.json that shows this code snippet as current work-around:

var builder = MauiApp.CreateBuilder();
        builder
            .RegisterBlazorMauiWebView()
            .UseMauiApp<App>()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
            })
            .ConfigureAppConfiguration((app, config) =>
            {
                var assembly = typeof(App).GetTypeInfo().Assembly;
                config.AddJsonFile(new EmbeddedFileProvider(assembly), "appsettings.json", optional: false, false);
            });

Note the use of EmbeddedFileProvider. This works with Build Action EmbeddedResource.


UPDATE to remove .Host, now that ConfigureAppConfiguration is directly on AppBuilder.


UPDATE 2 See Yepeekai's answer for newer solution. CAVEAT: I have not tested it though.

From .NET MAUI Preview 13, Host is removed (https://github.com/dotnet/maui/pull/4505). The exact same code in the accepted answer may not work.
Until appsettings.json is supported by MAUI (I hope the MAUI team will support it), I make my appsettings.json an Embedded resource and load and inject the contents like this.

var builder = MauiApp.CreateBuilder();

var assembly = Assembly.GetExecutingAssembly();

// appsettings.json is located directly under MyNamespace.csproj
using var stream = assembly.GetManifestResourceStream("MyNamespace.appsettings.json");
stream.Position = 0;
var appSettings = System.Text.Json.JsonSerializer.Deserialize<AppSettings>(stream);

builder.Services.AddSingleton(appSettings)

This may not be the best way to load the file but it works and it's good enough for me.
If there is a better way, I'd like to know it.

References: https://redth.codes/settings-json-files-in-xamarin-apps/

As of GA of MAUI: Add 2 nuget packages:

  • Microsoft.Extensions.Configuration.Binder
  • Microsoft.Extensions.Configuration.Json

then in MauiProgram.cs, add:

using var stream = Assembly.GetExecutingAssembly()
    .GetManifestResourceStream("YourAppName.appsettings.json");
var config = new ConfigurationBuilder().AddJsonStream(stream).Build();
builder.Configuration.AddConfiguration(config);

Reference: https://montemagno.com/dotnet-maui-appsettings-json-configuration/

Related