filemauiassetsitemgroup

How to include asset file in Maui Android


I've been trying out .NET Maui and so far it's been good. (Although the documentation is not particularly clear, but I have managed).

Now, my problem is this:

I'm trying to read from a txt file I placed in the Recources/Raw directory in a folder named txtFiles (so basically "Recources/Raw/txtFiles/fileIWant.txt")

Now in the documentation I've found the <ItemGroup> tag to include files.

I've also found the <MauiAsset> tag in a question on this site.

Normally I'm all about trial and error (I tend to learn and remember better that way), but I am seriously lost over where to place those tags.

I have placed them in all XAML files and even tried to use both tags, but to no avail. I still get a "file not found" error.

I hope you guys can help me!


Solution

  • You could use FileSystem.OpenAppPackageFileAsync method,

    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.

    You create a subfolder named txtFiles and place fileIWant.txt in it. You don't have to change the project file or add any tags in XAML, just ensure the Build Action of the fileIWant.txt as MauiAsset, and use OpenAppPackageFileAsync to access the file.

            using var stream = await FileSystem.OpenAppPackageFileAsync("txtFiles/fileIWant.txt");
            using var reader = new StreamReader(stream);
    
            var contents = reader.ReadToEnd();
    

    Since you create the subfolder, you may use txtFiles/fileIWant.txt as the parameter passed to the method.

    For more info, you may refer to File system helpers.