如何修复 Xamarin.forms System.IO.FileNotFoundException: 找不到文件
how to fix Xamarin.forms System.IO.FileNotFoundException: Could not find file
我正在使用 xamrin.forms,我正在尝试访问文件并读取它。
我有 lastusername.txt 作为文本文件,我将其构建操作设置为 "Content",实际上我正在尝试按以下方式读取文件:
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: Could not find file
将您的文件放在 Android Assets 文件夹中,并为其指定构建类型 "AndroidAsset".
由于您应用的资源是只读的,因此您可以通过 AssetManager
读取它,如果它不存在则将其保存(复制)到其他地方(即第一次应用 运行):
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);
下次应用 运行 时,您将在缓存目录中选择该应用。
我正在使用 xamrin.forms,我正在尝试访问文件并读取它。
我有 lastusername.txt 作为文本文件,我将其构建操作设置为 "Content",实际上我正在尝试按以下方式读取文件:
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: Could not find file
将您的文件放在 Android Assets 文件夹中,并为其指定构建类型 "AndroidAsset".
由于您应用的资源是只读的,因此您可以通过 AssetManager
读取它,如果它不存在则将其保存(复制)到其他地方(即第一次应用 运行):
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);
下次应用 运行 时,您将在缓存目录中选择该应用。