-3

I have JSON file in /resources/raw but when im trying to load i have error: System.IO.FileNotFoundException: 'Could not find file '/drinks.json'.' Code:

string drinksJsonData = File.ReadAllText("drinks.json");
    var drinks = JsonSerializer.Deserialize<List<drinksclass>>(drinksJsonData);
    if(drinks != null)
    {
        foreach(var drink in drinks)
            {
            await DisplayAlert("ALERT", "WORKING", "OK");
            }
    }

I have <MauiAsset Include="Resources\Raw\**" LogicalName="%(RecursiveDir)%(Filename)%(Extension)" /> and <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" /> in .csproj. I also tried change build settings but its still not working.

Zwolak9
  • 1
  • 1
  • 1
    https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/storage/file-system-helpers?tabs=android#bundled-files – Jason Sep 17 '22 at 22:11

1 Answers1

0

You can use method FileSystem.OpenAppPackageFileAsync to achieve this function.

Please refer to the following code:

private async void OnReadClicked(object sender, EventArgs e) 
      {
        var json = await LoadMauiAsset();
        await DisplayAlert("", json, "OK");
    }

    async Task<string> LoadMauiAsset()
    {
        try
        {
            using var stream = await FileSystem.OpenAppPackageFileAsync("fake.json");
            using var reader = new StreamReader(stream);

            return reader.ReadToEnd();
        }
        catch (Exception ex)
        {
            return "";
        }

    }

Note:please set the build action of your Jason to MauiAsset .

Jessie Zhang -MSFT
  • 9,830
  • 1
  • 7
  • 19