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

时间:2015-10-06 11:14:51

标签: c# android file xamarin

我正在使用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();
}

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

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

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

<小时/> 更新2:在外部存储上,它的工作原理与代码相同......可能是我设备的问题?那会很棒,因为我在我朋友的手机上测试了外部存储版本,但是我没有外部存储(OnePlus One),所以我还在寻找解决方案(如果有的话)。

1 个答案:

答案 0 :(得分:8)

终于找到了解决方案。

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 { ... }