I created a json file in the Resources/Raw and I made the build generation action to MauiAsset. I used the following code to load the json file but I got a not found file exception.
public partial class MainPage : ContentPage
{
int count = 0;
public MainPage()
{
InitializeComponent();
var json = LoadMauiAsset();
}
async Task LoadMauiAsset()
{
try
{
using var stream = await FileSystem.OpenAppPackageFileAsync("drugs.json");
using var reader = new StreamReader(stream);
var contents = reader.ReadToEnd();
}
catch (Exception ex)
{
}
}
}```
The code that you pasted won't even compile, or at the very least will never give you the result you're after. I have modified your code a bit and verified that this works.
private async void OnButtonClickedHandler(object sender, EventArgs e)
{
var json = await LoadMauiAsset();
await DisplayAlert("", json, "OK");
}
async Task<string> LoadMauiAsset()
{
try
{
using var stream = await FileSystem.OpenAppPackageFileAsync("foo.json");
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
catch (Exception ex)
{
return "";
}
}
As you already mentioned, you will need to add the drugs.json in the Resources\Raw\ file and mark it with the MauiAsset build action. To double-check, open your csproj file and make sure that this line is there: <MauiAsset Include="Resources\Raw\**" LogicalName="%(RecursiveDir)%(Filename)%(Extension)" /> this makes sure that everything under the afore mentioned folder is included as an asset.
and no other mention of your drugs.json file. There might be an entry like this:
<ItemGroup>
<None Remove="Resources\Raw\foo.json" />
</ItemGroup>
Which is fine, but you can remove it as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With