Xamarin File Handling Documentation - SpecialFolder.LocalApplicationData doesn't exist

Documentation for Xamarin says you can read a text file using the below:

File.ReadAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "score.txt"))

"score.txt" being a text file in my solution, however, when compiling and executing that code the file cannot be found:

FileNotFoundException

I can successfully read the text file in my solution with this:

using (var stream = await FileSystem.OpenAppPackageFileAsync("score.txt"))
using (var reader = new StreamReader(stream))

However I can't use a stream reader as I need to read the file when the app opens so it cannot be asynchronous.

What am I doing wrong or is the documentation wrong?

1 answer

  • answered 2018-10-11 19:58 SushiHangover

    File.ReadAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "score.txt"))

    LocalApplicationData is not the location of the native bundled assets. You need to copy it first out of the read only app bundle.

    However I can't use a stream reader as I need to read the file when the app opens so it cannot be asynchronous.

    You can do this in multiple areas change to the OnStart override in your Forms' Application subclass (typically App) to allow await

    protected async override void OnStart()
    {
       ...
    

    You could also do this in first page OnAppearing override:

    protected async override void OnAppearing()
    {
       ...
    

    Xamarin.Essentials OpenAppPackageFileAsync returns a stream to a "native" Android Asset or iOS bundle resource, etc.. so you will need copy your score.txt file into the native projects

    Android:

    Add/copy the score.txt to your Xamarin.Android project Assets with a build action of AndroidResource

    enter image description here

    iOS:

    Add/copy the score.txt to your Xamarin.iOS projects Resources (technically anywhere, but for organization Resources works well) with a build action of BundleResource

    enter image description here