引言:
按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
關聯專案
FreeSql QQ群:4336577、8578575、52508226
BA & Blazor QQ群:795206915、675147445
知識共享許可協議
本作品采用 知識共享署名-非商業性使用-相同方式共享 4.0 國際許可協議 進行許可,歡迎轉載、使用、重新發布,但務必保留文章署名AlexChow(包含鏈接: https://github.com/densen2014 ),不得用于商業目的,基于本文修改后的作品務必以相同的許可發布,如有任何疑問,請與我聯系 ,
AlexChow
今日頭條 | 博客園 | 知乎 | Gitee | GitHub
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/533465.html
標籤:C#
