【问题标题】:Android text file not found未找到 Android 文本文件
【发布时间】:2018-09-29 02:42:54
【问题描述】:

我的解决方案中有一个名为“txtWords.txt”的文本文件,我尝试使用它来阅读:

string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

string filePath = Path.Combine(path, "txtWords.txt");

在我的实验中,我的 C# App 和 App.Android > Assets 文件夹下都有相同的文件(设置为 AndroidAsset)。为了安全起见,我想把它放在这两个位置。

System.IO.FileNotFoundException: Could not find file "/data/user/0/com.WSC/files/txtWords.txt"

我已经阅读了有关使用 AssetManager 的信息,但这给了我一个“找不到命名空间错误”。

我做错了什么以及为应用读取文本文件的最佳方式是什么?这应该真的很容易,所以我想我做错了一些相当基本的错误。

【问题讨论】:

  • 您是尝试从 PCL/NetStd (Xamarin.Forms) 库还是 Xamarin.Android 库中执行此操作
  • 解决方案中的文件不包含在个人文件夹中,它将嵌入到应用程序包中。对于 Android,完成您想要的最佳方式是使用资产
  • 有没有很好的使用Assets的例子?我试过但不明白如何正确使用 Asset 命名空间。

标签: c# android xamarin xamarin.forms


【解决方案1】:

使用 Xamarin Essentials,您可以通过 NetStd (Xamarin.Forms) 库读取捆绑/资产只读文件:

string wordsText;
using (var stream = await FileSystem.OpenAppPackageFileAsync("txtWords.txt"))
using (var reader = new StreamReader(stream))
{
    var wordsText = await reader.ReadToEndAsync();
}

回复:https://docs.microsoft.com/en-us/xamarin/essentials/file-system-helpers?tabs=android

Nuget:https://www.nuget.org/packages/Xamarin.Essentials

【讨论】:

  • 谢谢。这似乎是答案。尽管奇怪的是,即使正在使用 OpenAppPackFileAsync,我现在也收到“'await' 运算符只能在异步方法中使用”错误。这是一个需要调查的单独问题!
猜你喜欢
  • 2021-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-12
  • 1970-01-01
  • 2021-08-05
  • 1970-01-01
相关资源
最近更新 更多