Xamarin表单:在Android设备的内部存储中写入文件

时间:2017-05-12 07:31:49

标签: android file xamarin.android xamarin.forms

我正在使用Xamarin Forms PCL项目开发一个跨平台的应用程序。在这里我需要在Android的内部存储中写一个文件,以便我可以访问它。我已经将Write写入了“外部存储”权限,但是当我尝试编写该文件时,它表示Access被拒绝。

以下是我的尝试:

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();
        }
    }
}

1 个答案:

答案 0 :(得分:5)

  

在这里,我需要在android的内部存储中写一个文件,以便我可以访问它。我已经将Write写入了“外部存储”权限,但是当我尝试编写该文件时,它表示Access被拒绝。

首先,权限<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />用于外部存储,因此它不适用于内部存储。

根据您的代码:

Java.IO.File DataDirectoryPath = Android.OS.Environment.DataDirectory; 

您使用Data Directory进行撰写,此目录由系统拥有,无权写入,在SO上就此问题进行了多次讨论,例如:{{3} }。

因此,正如它在答案中所建议的那样,您可以使用getFilesDir()在内部存储中写入,在Xamarin中,它是Data directory has no read/write permission in Android

<强>更新

我根据你的代码编写了一些代码,它应该是相同的,例如:

var dirPath = this.FilesDir + "/MyFolder";
var exists = Directory.Exists(dirPath);
var filepath = dirPath + "/test.txt";
if (!exists)
{
    Directory.CreateDirectory(dirPath);
    if (!System.IO.File.Exists(filepath))
    {
        var newfile = new Java.IO.File(dirPath, "test.txt");
        using (FileOutputStream outfile = new FileOutputStream(newfile))
        {
            string line = "The very first line!";
            outfile.Write(System.Text.Encoding.ASCII.GetBytes(line));
            outfile.Close();
        }
    }
}

我还通过DDMS检查了这个文件,可以在文件夹下找到:data\data\yourAPP\files\MyFolder\test.txt

Android.Content.Context.FilesDir Property

我只测试了Xamarin.Android项目,没有尝试将DependencyService用于Xamarin.Forms,如果您尝试这样做,只需替换this中的单词 let username = "DavidMouse" // create searchRef or queryRef you name it let searchRef = FIRDatabase.database().reference().child("users").queryOrdered(byChild: "username").queryEqual(toValue: username) // search the username searchRef.observeSingleEvent(of: .value, with: { (snapshot) in guard snapshot.value is NSNull else { // yes we got the user let user = snapshot.value as! String print("\(user) is exists") return } // no there is no user with desire username print("\(username) is exists") }) { (error) in print("Failed to get snapshot", error.localizedDescription) } 上面的代码到你的android上下文。