Android Assets folder does not get recognized

Viewed 255

I am doing a Xamarin Forms project with iOS and Android, and I am trying to retrieve a txt file from the assets folder for Android and from the Resources folder in iOS. It works for iOS but it doesn't work for Android. To be exact, in the Android project, the path for my text file is "Assets/versions/latestVersion.txt"

I have this Base URL for Android:

[assembly: Dependency(typeof(BaseUrl_Android))]
namespace WorkingWithWebview.Android
{
    public class BaseUrl_Android : IBaseUrl
    {
        public string Get()
        {
            return "file:///android_asset/";
        }
    }
}

Now, in my code, I have:

string versioningFile = Xamarin.Forms.DependencyService.Get<IBaseUrl>().Get();
string path = Path.Combine(versioningFile, "versions/latestVersion.txt");

string file = File.ReadAllText(path);

My IBaseUrl is

public interface IBaseUrl { string Get(); }

It doesn't recognize the path, the error states "Could not find a part of the path /file:/android_asset/versions/latestVersion.txt".

What is the problem ? The path is clearly what i want it to be.

1 Answers

About Assete,it's read using an AssetManager.

You could also use File System Helpers of Xamarin.Essentials.

using (var stream = await FileSystem.OpenAppPackageFileAsync(fileName))
{
   using (var reader = new StreamReader(stream))
   {
    var fileContents = await reader.ReadToEndAsync();
   }
}

Note: Add any file into the Assets folder in the Android project and mark the Build Action as AndroidAsset

Related