如何在 .NET MAUI 中加载 json 文件?

引言:

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

bec587fbc798ec003e5215854a5d3770.png

资源文件夹
  1. 官方工程 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文件按操作复现成功.

  1. 直接丢入 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 文件

cb46bf168b78a034cfa33a5b70be5d8d.png

项目文件

<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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值