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

99封情书 提交于 2019-12-08 12:10:13

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/38824812/how-to-fix-xamarin-forms-system-io-filenotfoundexception-could-not-find-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!