Xamarin Android "Permission Denied" when saving a bitmap

2

I have a bitmap that I want to store in the device (either internally or externally) it worked correctly, but when I try to save it it marks me the following error:

System.UnauthorizedAccessException: Access to the path "/storage/emulated/0/imagen.png" is denied.

This is where I try to save it:

var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filePath = System.IO.Path.Combine(sdCardPath, "imagen.png");
var stream = new FileStream(filePath, FileMode.Create);
img.Compress(Bitmap.CompressFormat.Png, 100, stream);
stream.Close();

Where img is the bitmap.

I have already enabled the permissions with:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

But still not let me save on that route, any suggestions?

    
asked by EriK 19.12.2017 в 17:10
source

1 answer

-1

The problem you indicate

  

System.UnauthorizedAccessException

is because you should remember that from Android 6.0, the request for permissions as:

WRITE_EXTERNAL_STORAGE

must be done manually at runtime and it is not enough to declare Permissions in the file Manifest.xml .

Check the official documentation for an example of this.

p>

I add an example of how to make the request for the permissions WriteExternalStorage and ReadExternalStorage in Xamarin :

     //Define permisos requeridos por aplicación.
  readonly string [] PermissionsMyApp = 
    {
      Manifest.Permission.WriteExternalStorage,
      Manifest.Permission.ReadExternalStorage
    };

    const int RequestExternalStorageId = 0;

    const string permission = Manifest.Permission.WriteExternalStorage;
    if (CheckSelfPermission(permission) == (int)Permission.Granted)
    {
      //Ya se cuenta con permisos!
      return;
    }


     //Se necesita obtener permiso,
      if (ShouldShowRequestPermissionRationale(permission))
      {
        //Explica al usuario porque necesita el permiso.
        Snackbar.Make(layout, "Permiso requerido para el correcto funcionamiento de la aplicación.", Snackbar.LengthIndefinite)
                .SetAction("OK", v => RequestPermissions(PermissionsMyApp, RequestExternalStorageId ))
                .Show();
        return;
      }

  //Finalmente requiere el permiso  permissions and Id
  RequestPermissions(PermissionsMyApp, RequestExternalStorageId);
    
answered by 19.12.2017 в 17:45