简体   繁体   中英

Access to the path denied when trying to create a file on external storage

I want my android app to save a text file with the contents from an EditText . When I do as follows, the new files are saved as expected:

string[] filename = new string[50];
EditText et1 = FindViewById<EditText>(Resource.Id.editText1);
EditText et2 = FindViewById<EditText>(Resource.Id.editText2);
string doc = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
filename[0] = Path.Combine(doc, "Text1");
filename[1] = Path.Combine(doc, "Text2");
File.WriteAllText(filename[0], et1.Text);
File.WriteAllText(filename[1], et2.Text);

But if I change the filename as follows:

filename[0] = Path.Combine(doc, 1.ToString());
filename[1] = Path.Combine(doc, 2.ToString());

The app will combine the determined address but it can not write data there and throws the following exception:

Error: Access to this address denied

How I can solve this problem?

I tried reproducing the issue using your code but could not. This tells me that the problem doesn't lie within your code.

I was although running on an emulator which may just be the key difference.

When you're trying to access an external storage , make sure that you have set the following permission in your manifest:

WRITE_EXTERNAL_STORAGE (writing)
READ_EXTERNAL_STORAGE (reading)

In any case, you should really consider if you specifically want to place the data on the external SD card. That may cause issues for users whom don't have one installed. Instead, you can do as follows to access the internal storage as written in Xamarin's documentation for best practices in regards to the storing content on the file system:

System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)

You're exception is because you forgot the permissions in your AndroidMnaifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="yournamespace">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <application .../>
</manifest>

You can make a method writeText() and call it twice. You can use an other folder with

string path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath;

        writeText(et1.Text, "Text1.txt");
        writeText(et2.Text, "Text2.txt");

    void writeText(string text, string name) {
         string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
         string filename = Path.Combine(path, name);

         using(var streamWriter = new StreamWriter(filename, true)) {
          streamWriter.Write(text);
         }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM