引言:
按.NET core传统方式添加 AddJsonFile("appsettings.json") 在windows平台和ssr工作正常,但是在 ios 和 android 无法用这种方式,因为资源生成方式不一样. 使用内置资源方式不够灵活而且 ios 平台会提示不能复制 json 文件到目录,于是进行了几天的研究,终于能正确使用了.

资源文件夹
- 官方工程 - Resources\Raw\文件夹- AboutAssets.txt文件说明
您希望与应用程序一起部署的任何原始资产都可以放置在此目录(和子目录)。将资产部署到您的应用程序, 由 `.csproj` 中的以下 `MauiAsset` 构建操作自动处理。<MauiAsset Include="Resources\Raw\**" LogicalName="%(RecursiveDir)%(Filename)%(Extension)" />这些文件将与您的包一起部署,并且可以使用 Essentials 访问:async Task LoadMauiAsset(){using var stream = await FileSystem.OpenAppPackageFileAsync("AboutAssets.txt");using var reader = new StreamReader(stream);var contents = reader.ReadToEnd();}复制一份txt文件按操作复现成功.
- 直接丢入 appsettings.json 编译到ios平台提示错误不能复制 json 文件到目录, 经google,找到方案,需要项目文件属性中 Remove 文件 - <Content Remove="appsettings.json" />
相关错误提示
The path 'XXXXXXX\appsettings.json' would result in a file outside of the app bundle and cannot be used.
The path '..\..\..\..\..\..\..\Repos\BlazorMaui\BlazorMaui\appsettings.json' would result in a file outside of the app bundle and cannot be used.
最终方案:
- appsettings.json文件直接放工程根目录 
- 文件属性生成操作为 MauiAsset 和 不复制 
- 需要在项目属性中 Remove 文件 

项目文件
<ItemGroup><Content Remove="appsettings.json" /></ItemGroup><ItemGroup><MauiAsset Include="appsettings.json"><CopyToOutputDirectory>Never</CopyToOutputDirectory></MauiAsset></ItemGroup>读取配置文件代码
async static Task<Stream> LoadMauiAsset(){try{using var stream = await FileSystem.OpenAppPackageFileAsync("appsettings.json");using var reader = new StreamReader(stream);var contents = reader.ReadToEnd();Console.WriteLine("OpenAppPackageFileAsync => " + contents);return stream;}catch (Exception e){Console.WriteLine("OpenAppPackageFileAsync Exception => " + e.Message);}return null;}附加到 builder.Configuration
var stream = LoadMauiAsset().Result; 
builder.Configuration.AddJsonStream(stream);附:使用内置资源方式
需要在项目属性中设置生成操作为嵌入资源
<ItemGroup><EmbeddedResource Include="appsettings.json" />
</ItemGroup>代码 BlazorMaui 为工程名
var a = Assembly.GetExecutingAssembly();
using var stream = a.GetManifestResourceStream("BlazorMaui.appsettings.json");
builder.Configuration.AddJsonStream(stream);项目地址
https://github.com/densen2014/BlazorMaui
https://gitee.com/densen2014/BlazorMaui