Can't write to Android External storage even with permissions set

Viewed 4087

In my Android 10.0 (Q) app using Xamarin Forms I have correctly set in my manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest **** />
    <application *** ></application>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>

I have permissions granted in via code

var permission = ActivityCompat.CheckSelfPermission(MainActivity.Instance, Manifest.Permission.WriteExternalStorage);

if (permission != Permission.Granted)
{
    ActivityCompat.RequestPermissions(
      MainActivity.Instance, 
      new[] 
      { 
         Manifest.Permission.WriteExternalStorage, 
         Manifest.Permission.ReadExternalStorage 
      }, 1);
}

Yet when I try to create a file in my documents or pictures folder I get a permissions denied error: Java.IO.FileNotFoundException: '/storage/emulated/0/Documents/file.txt: open failed: EACCES (Permission denied)' What am I missing?

var folder= Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments);
folder.Mkdirs();

var filePath = Path.Combine(folder.AbsolutePath, filename);

// I get a permissions error here 
using (var stream = new Java.IO.FileOutputStream(filePath))
{
     await stream.WriteAsync(data).ConfigureAwait(false);
}
1 Answers

Before your app is fully compatible with scoped storage, you can temporarily opt out based on your app's target SDK level or the requestLegacyExternalStorage manifest attribute:

Google has a new feature on Android Q: filtered view for external storage. A quick fix for that is to add this code in the AndroidManifest.xml file:

<manifest ... >
  <!-- This attribute is "false" by default on apps targeting
    Android 10 or higher. -->
  <application android:requestLegacyExternalStorage="true" ... >
   ...
 </application>
</manifest>
Related