Jas*_*yne 6 android xamarin.forms .net-core maui
I have a small MAUI app i'm testing with. Im trying to read a file that was part of the deployment. I have the code below, which works great in a Windows deploy of the MAUI app, but crashes in Android. What is the proper cross-platform way to do this?
// TODO get from service or xml
var path = AppDomain.CurrentDomain.BaseDirectory;
//var path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
var fullpath = Path.Combine(path, "Services\\questions.json");
var json = File.ReadAllText(fullpath);
Run Code Online (Sandbox Code Playgroud)
MAUI has a new way to access files included with the app: MauiAsset.
UPDATE: More detail in Resource Files section of Maui doc.
Early description in blog Announcing .NET MAUI Preview 4, Raw Assets:
.NET MAUI now makes it very easy to add other assets to your project and reference them directly while retaining platform-native performance. For example, if you want to display a static HTML file in a WebView you can add the file to your project and annotate it as a MauiAsset in the properties.
<MauiAsset Include="Resources\Raw\index.html" />
Run Code Online (Sandbox Code Playgroud)
Tip: you can also use wildcards to enable all files in a directory:
... Include="Resources\Raw\*" ...
Run Code Online (Sandbox Code Playgroud)
Then you can use it in your application by filename.
<WebView Source="index.html" />
Run Code Online (Sandbox Code Playgroud)
MauiAssetPage.xaml:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MauiTests.MauiAssetPage">
<ContentPage.Content>
<!-- By the time Maui is released, this is all you will need. -->
<!-- The Init code-behind won't be needed. -->
<WebView x:Name="MyWebView" Source="TestWeb.html" />
</ContentPage.Content>
</ContentPage>
Run Code Online (Sandbox Code Playgroud)
MauiAssetPage.xaml.cs:
using Microsoft.Maui.Controls;
using System.Threading.Tasks;
namespace MauiTests
{
public partial class MauiAssetPage : ContentPage
{
public MauiAssetPage()
{
InitializeComponent();
// *** Hopefully this block of code no longer needed for WebView Source. ***
Device.BeginInvokeOnMainThread(async () =>
{
await InitAsync();
});
}
// *** Hopefully this is no longer needed. ***
private async Task InitAsync()
{
string filePath = "TestWeb.html";
var stream = await FileSystem.OpenAppPackageFileAsync(filePath);
if (stream != null)
{
string s = (new System.IO.StreamReader(stream)).ReadToEnd();
this.MyWebView.Source = new HtmlWebViewSource { Html = s };
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
TestWeb.html:
(whatever html you want)
Run Code Online (Sandbox Code Playgroud)
In Solution Explorer, add TestWeb.html to your project. In its Properties, select Build Action = MauiAsset.
| 归档时间: |
|
| 查看次数: |
9975 次 |
| 最近记录: |