9

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);
}
Michael S. Scherotter
  • 10,715
  • 3
  • 34
  • 57

1 Answers1

9

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>
Leo Zhu
  • 15,726
  • 1
  • 7
  • 23
  • 1
    in Android 11, setting this flag doesn't help. can you please help me with this https://stackoverflow.com/questions/66560359/xamarin-forms-how-to-define-scoped-storage-for-android-and-how-can-i-implement – Monica Mar 12 '21 at 12:45