Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a json file in .NET MAUI? [duplicate]

Tags:

json

maui

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)
        {

        }
        
    }
}```
like image 539
Maher Avatar asked Oct 29 '25 17:10

Maher


1 Answers

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.

like image 105
Gerald Versluis Avatar answered Nov 01 '25 08:11

Gerald Versluis