[英]Xamarin Android, read a simple text file from internal storage/Download
我正在使用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
终于找到了解决方案。
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 { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.