Xamarin Android,读取一个简单的文本文件从内部存储/下载

本文关键字:文件 文本 内部 下载 存储 简单 一个 读取 Android Xamarin | 更新日期: 2023-09-27 18:16:18

我正在使用Xamarin,根据之前的答案,这应该可以工作:

string path = Path.Combine(Android.OS.Environment.DirectoryDownloads, "families.txt");
File.WriteAllText(path, "Write this text into a file!");

但是它没有,我得到一个未处理的异常。我已经设置了读写外部存储的权限(即使这是内部的)。

我也试过这样做:

string content;
using (var streamReader = new StreamReader(@"file://" + path )) // with and without file://
{
    content = streamReader.ReadToEnd();
}

但是我得到了相同的未处理异常。


UPDATE:路径是问题所在,因为我在这里得到了else部分:

Java.IO.File file = new Java.IO.File(path);
if (file.CanRead())
    testText.Text = "The file is there";
else
    testText.Text = "The file is NOT there'n" + path;

这很奇怪,因为路径似乎是正确的。无法找到路径的一部分:/Download/families.txt


UPDATE2:在外部存储上,它可以工作,使用相同的代码…可能是我的设备出了问题?这太好了,因为我在朋友的手机上测试了外置存储版本,但我的手机没有外置存储(一加一),所以我仍在寻找解决方案(如果有的话)。

Xamarin Android,读取一个简单的文本文件从内部存储/下载

终于找到解决办法了

var path = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filename = Path.Combine(path.ToString(), "myfile.txt");

路径是问题所在,现在有了一个简单的流写入器,它就像魔术一样工作了。

try
{
      using (var streamWriter = new StreamWriter(filename, true))
      {
             streamWriter.WriteLine("I am working!");
      }
}
catch { ... }