slodki1997
slodki1997

Reputation: 21

Problem with .NET MAUI Blazor and RCL. How to take static files?

I've created a solution, which contains two projects: BlazorMAUIApp (project in .NET MAUI Blazor - NOT Blazor Server or not Blazor WASM!) and BlazorAppCore (project Razor Class Library).

One of the most important functionalities of my app is access to static files in RCL project from BlazorMAUIAPP. I have files in wwwroot/sample-data and I need to get this file to stream (or byte[]). What's important - I want to create multiplatform app. My destination are Windows and Android.

I've set my static files in RCL as "embedded resource" and "always copy". Then I've used to FileSystem.OpenAppPackageFileAsync(path) method, where path is string, which structure is "wwwroot/sample-data/{file name}". When I try to compile it on Windows - it works! However, when I want to compile and run app on Android - I receive exception.

What is the problem? I've heard MAUI should be multiplatform technology, but I start to doubt it...

Upvotes: 1

Views: 674

Answers (2)

Yu-Core
Yu-Core

Reputation: 1

There is a problem with your path

The correct path should be

wwwroot/_content/{Rcl project name or Rcl package name}/sample-data/{file name}

Please read Microsoft's document

https://learn.microsoft.com/aspnet/core/blazor/hybrid/static-files?view=aspnetcore-7.0#static-assets-limited-to-razor-components

Upvotes: 0

Guangyu Bai - MSFT
Guangyu Bai - MSFT

Reputation: 4486

You can put the ReadData method to the @Code block.

   private async Task<string> ReadData()
    {
        using var stream = await FileSystem.OpenAppPackageFileAsync("wwwroot/data.txt");
        using var reader = new StreamReader(stream);
    
        return await reader.ReadToEndAsync();
    }

Due to the method FileSystem.OpenAppPackageFileAsync, Files that were added to the project with the Build Action of MauiAsset can be opened with this method. .NET MAUI projects will process any file in the Resources\Raw folder as a MauiAsset.

Here is the document about File system helpers in Maui.

Upvotes: 0

Related Questions