2015-10-06 57 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 { ... } 
相關問題