如何修复Xamarin.forms System.IO.FileNotFoundException:找不到文件 [英] how to fix Xamarin.forms System.IO.FileNotFoundException: Could not find file
问题描述
我正在使用 xamrin.forms ,并且正在尝试访问文件并读取它.
I am using xamrin.forms, and I am trying to access file and read it.
我将lastusername.txt作为文本文件,并将其构建操作设置为"Content",实际上我正在尝试按以下方式读取文件:
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 "";
我收到以下错误:
System.IO.FileNotFoundException:找不到文件
System.IO.FileNotFoundException: Could not find file
推荐答案
将文件放置在Android Assets 文件夹中,并将其分配给构建类型为"AndroidAsset".
Place your file within the Android Assets folder and assign it with a build type of "AndroidAsset".
由于您的应用程序资产是只读的,因此您可以通过AssetManager
对其进行读取,如果不存在(例如,该应用程序首次运行),则可以将其保存(复制)到其他位置:
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.
这篇关于如何修复Xamarin.forms System.IO.FileNotFoundException:找不到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!