2015-10-06 165 views
2

我使用Xamarin,并根据以前的答案,这应工作:Xamarin的Android,读取内部存储的简单文本文件/下载

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:的路径是问题,因为我得到的其他部分在这里:

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:外部存储上,它的工作原理,使用相同的代码......也许这是我的设备的问题?这很好,因为我在朋友的手机上测试了外部存储版本,但我的外部存储没有(OnePlus One),所以我仍在寻找解决方案(如果有的话)。

+0

你所得到的具体例外是什么? – Jason

+0

如果使用“Break”选项,它应该让您检查Exception对象以确定导致它的具体错误。 – Jason

+0

你可以登录路径吗? – Johan

回答

5

终于找到了解决办法。

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

的路径是问题,现在用一个简单的StreamWriter它就像魔法。

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