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
There is an open issue Add support for appsetting.json.
This code snippet from issue 3446 is one 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 in above code, removed use of .Host
, now that ConfigureAppConfiguration
is directly on AppBuilder.
UPDATE 2 See Yepeekai's answer for newer solution. CAVEAT: I have not tested it though.
UPDATE 3 James Montemagno’s code to support appsettings.json. This link is from a comment in the open issue.