how do you set permissions to list directories in a xamarin form application?

If the Android 6 (API 23) or higher, the permission is requested at the run time during the runnnig of the app.

Try to request the WriteExternalStorage runtime permission.

in your MainActivity:

protected override void OnCreate(Bundle savedInstanceState)
    {
       ...
      if (CheckSelfPermission( Manifest.Permission.WriteExternalStorage) == Permission.Granted)
      {
         string szPicturesDirectory = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).AbsolutePath;
         var dirs = Directory.EnumerateDirectories(szPicturesDirectory);
         List<string> workDirs = new List<string>(dirs);
      }
      else
      {
         ActivityCompat.RequestPermissions(Instance, new string[] { Manifest.Permission.WriteExternalStorage }, 1);
      }
     ...
    }

 public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
    {
        Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1)
        {
            if (grantResults[0] == Permission.Granted)
            {
                string szPicturesDirectory = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).AbsolutePath;
                var dirs = Directory.EnumerateDirectories(szPicturesDirectory);
                List<string> workDirs = new List<string>(dirs);
            }
        }
    }

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top