Search code examples
c#xamarinxamarin.androidxamarin.formsportable-class-library

how to fix Xamarin.forms System.IO.FileNotFoundException: Could not find file


I am using xamrin.forms, and I am trying to access file and read it.

I have lastusername.txt as text file and I set the build action for it as "Content", actually I am trying to read file as the following:

  var filename = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "lastusername.txt");
    if (filename != null)
           return System.IO.File.ReadAllText(filename);//error occurred here 
    else
           return "";

I get the following Error:

System.IO.FileNotFoundException: Could not find file


Solution

  • Place your file within the Android Assets folder and assign it with a build type of "AndroidAsset".

    Since your app's assets are read-only, you can then read it via the AssetManager, saving (copy) it somewhere else if it does not exist (i.e. the first time the app is run):

    var fileName = "MyAssetBasedFile.txt";
    if (!File.Exists(Path.Combine(CacheDir.Path, fileName)))
    {
        AssetManager assets = this.Assets;
        using (StreamReader sr = new StreamReader(assets.Open(fileName)))
        using (StreamWriter sw = new StreamWriter(Path.Combine(CacheDir.Path, fileName), append: false))
            sw.Write(sr.ReadToEnd());
    }
    string content;
    using (StreamReader sr = new StreamReader(Path.Combine(CacheDir.Path, fileName)))
    {
        content = sr.ReadToEnd();
    }
    Log.Debug("SO", content);
    

    The next time the app runs you will pick up the one in your cache dir.