我正在開發一個使用Xamarin Forms PCL項目的跨平臺應用程序。在此我需要在Android的內部存儲器中編寫一個文件,以便我可以訪問它。我給了寫入外部存儲權限,但是當我嘗試寫入文件時,它說Access被拒絕。Xamarin Forms:在Android設備的內部存儲器中寫入文件
這裏是我的嘗試:
Java.IO.File DataDirectoryPath = Android.OS.Environment.DataDirectory;
string dirPath = DataDirectoryPath.AbsolutePath + "/MyFolder";
bool exists = Directory.Exists(dirPath);
string filepath = dirPath + "/test.txt";
if (!exists)
{
Directory.CreateDirectory(dirPath);
if (!File.Exists(filepath))
{
File.Create(filepath).Dispose();
using (TextWriter tw = new StreamWriter(filepath))
{
tw.WriteLine("The very first line!");
tw.Close();
}
}
}
通常建議(和安全)使用應用程序的沙箱來存儲文件。如果您將文件存儲到設備存儲,而您的文件可以很容易地修改/刪除... – Milen
'Directory.CreateDirectory(dirPath);'你不應該檢查返回值嗎?或者在試圖放入一個文件之前檢查目錄是否存在? – greenapps
它說「訪問被拒絕」 – Sonali