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

hun*_*ude 4 c# android file xamarin

我正在使用Xamarin,根据之前的答案,这应该有效:

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

但它没有,我得到和未处理的异常.我已设置读取和写入外部存储的权限(即使这是内部存储).

我也试过这个:

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

但我得到了同样未处理的例外.


更新:路径是问题,因为我在这里得到了其他部分:

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;
Run Code Online (Sandbox Code Playgroud)

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


UPDATE2:在外部存储上,它的工作原理与代码相同......可能是我设备的问题?这将是伟大的,因为我在我朋友的手机上测试了外部存储版本,但我没有外部存储(OnePlus One),所以我仍在寻找解决方案(如果有的话).

hun*_*ude 8

终于找到了解决方案.

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

路径是问题所在,现在有一个简单的编写器就像魔术一样.

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