在 .NET MAUI 中加載 json 文件的方法
目錄
- 引言:
- 資源文件夾
- 附:使用內(nèi)置資源方式
- 項目地址
引言:
按core傳統(tǒng)方式添加 AddJsonFile("appsettings.json") 在windows平臺和ssr工作正常,但是在 ios 和 android 無法用這種方式,因為資源生成方式不一樣. 使用內(nèi)置資源方式不夠靈活而且 ios 平臺會提示不能復(fù)制 json 文件到目錄,于是進(jìn)行了幾天的研究,終于能正確使用了.
資源文件夾
- 官方工程
Resources\Raw\
文件夾AboutAssets.txt
文件說明
您希望與應(yīng)用程序一起部署的任何原始資產(chǎn)都可以放置在此目錄(和子目錄)。 將資產(chǎn)部署到您的應(yīng)用程序, 由 `.csproj` 中的以下 `MauiAsset` 構(gòu)建操作自動處理。 <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(); }
復(fù)制一份txt文件按操作復(fù)現(xiàn)成功.
- 直接丟入 appsettings.json 編譯到ios平臺提示錯誤不能復(fù)制 json 文件到目錄, 經(jīng)google,找到方案,需要項目文件屬性中 Remove 文件
<Content Remove="appsettings.json" />
相關(guān)錯誤提示
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 和 不復(fù)制
- 需要在項目屬性中 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);
附:使用內(nèi)置資源方式
需要在項目屬性中設(shè)置生成操作為嵌入資源
<ItemGroup> <EmbeddedResource Include="appsettings.json" /></ItemGroup>
代碼 BlazorMaui
為工程名
var a = Assembly.GetExecutingAssembly();using var stream = a.GetManifestResourceStream("BlazorMaui.appsettings.json");builder.Configuration.AddJsonStream(stream);
項目地址
到此這篇關(guān)于如何在 .NET MAUI 中加載 json 文件?的文章就介紹到這了,更多相關(guān).NET MAUI 加載 json 文件內(nèi)容請搜索以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持!
