androidmauiandroid-assets

MAUI - Android - How to read asset files?


I am developing a MAUI project with VS2022. My issue comes with this snipped where I try to read two files from disk and use them as parameters for another function.

CopyFileToAppDataDirectory("vocab.json");
CopyFileToAppDataDirectory("merges.json");
var tokenizer = new Tokenizer(new Bpe(GetAssetFilePath("vocab.json"), GetAssetFilePath("merges.txt")));

Both files are part of the project, I copied them in a folder called Assets inside the Android folder. enter image description here

The function Bpe throws an exception indicating that the file does not exist in the location.

System.IO.FileNotFoundException: 'Could not find file '/data/user/0/com.companyname.familytunesv3/files/vocab.json'.'

Both files have the build action set to "EmbeddedResource" and "Copy Always" enter image description here

the code of the auxiliary functions

public async Task CopyFileToAppDataDirectory(string filename)
{
// Open the source file
using Stream inputStream = await FileSystem.Current.OpenAppPackageFileAsync(filename);
    
// Create an output filename
string pathfile = FileSystem.Current.AppDataDirectory + "/files/";
string targetFile = Path.Combine(pathfile, filename);
    
// Copy the file to the AppDataDirectory
using FileStream outputStream = File.Create(targetFile);
await inputStream.CopyToAsync(outputStream);
}


string GetAssetFilePath(string assetFileName)
{
var assetPath = Path.Combine(FileSystem.AppDataDirectory,assetFileName);
return assetPath;
}

any idea how to make it work?

thanks a lot.


Solution

  • I solved by setting the build action to "MauiAsset" and using the function

    public async Task CopyFileToAppDataDirectory(string filename)
    {
        // Open the source file
        using Stream inputStream = await FileSystem.Current.OpenAppPackageFileAsync(filename);
    
        // Create an output filename
        string targetFile = Path.Combine(FileSystem.Current.AppDataDirectory, filename);
    
        // Copy the file to the AppDataDirectory
        using FileStream outputStream = File.Create(targetFile);
        await inputStream.CopyToAsync(outputStream);
    }
    

    the final code was like this

     await CopyFileToAppDataDirectory("vocab.json");
     await CopyFileToAppDataDirectory("merges.txt");
      
     var tokenizer = new Tokenizer(new Bpe(GetAssetFilePath("vocab.json"), GetAssetFilePath("merges.txt")));