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

引言:按core傳統方式添加 AddJsonFile("appsettings.json") 在windows平臺和ssr工作正常,但是在 ios 和 android 無法用這種方式,因為資源生成方式不一樣. 使用內置資源方式不夠靈活而且 ios 平臺會提示不能復制 json 文件到目錄,于是進行了幾天的研究,終于能正確使用了.

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

文章插圖
資源文件夾
  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.
最終方案:
  • appsettings.json文件直接放工程根目錄
  • 文件屬性生成操作為 MauiAsset 和 不復制
  • 需要在項目屬性中 Remove 文件

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

文章插圖
項目文件
    <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;        }

經驗總結擴展閱讀