При записи в папку загрузок возникает ошибка. Ошибка открытия EPERM. Операция запрещена. - PullRequest
0 голосов
/ 14 июля 2020

Я пишу приложение Xamarin. Android, но ответа на нативном Android будет достаточно. Я пытаюсь сохранить файл pdf (который я скачал как байт []) в папку «Загрузки». Вот мой код:

File path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
var file = new File(path, "myfile.pdf");

using (var output = new FileOutputStream(file))
{
    try
    {
        await output.WriteAsync(theByteArray);
    }
    catch (Exception ex)
    {
                
    }
}

Я получаю сообщение об ошибке:

/ storage / emulated / 0 / Download / myfile.pdf: open failed: EPERM (операция запрещена)

Я проверил WriteExternalStorage в AndroidManifest. xml

1 Ответ

1 голос
/ 14 июля 2020

Начиная с Android 6.0 (уровень API 23), Android устройству требуются разрешения времени выполнения.

Если вам нужно разрешение на хранение, вы можете использовать приведенный ниже код для запроса.

public class Activity1 : Activity
{
    public string TAG
    {
        get
        {
            return "Activity1";
        }
    }
    static readonly int REQUEST_STORAGES = 1;
    static string[] PERMISSIONS_STORAGES = {
        Manifest.Permission.ReadExternalStorage,
        Manifest.Permission.WriteExternalStorage
    };

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Create your application here

        SetContentView(Resource.Layout.layout2);
        var request_permission = FindViewById<Button>(Resource.Id.btn_request_permission);
        var save = FindViewById<Button>(Resource.Id.btn_save);
        layout = FindViewById(Resource.Id.layout2);

        request_permission.Click += delegate
        {
            Log.Info(TAG, "Show Storage button pressed. Checking permissions.");

            // Verify that all required contact permissions have been granted.
            if (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) != (int)Permission.Granted
                || ActivityCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted)
            {
                // Contacts permissions have not been granted.
                Log.Info(TAG, "Storage permissions has NOT been granted. Requesting permissions.");
                RequestContactsPermissions();
            }
            else
            {
                // Contact permissions have been granted. Show the contacts fragment.
                Log.Info(TAG, "Storage permissions have already been granted.");

            }
        };

        save.Click += async delegate
        {

            if (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) == (int)Permission.Granted
               || ActivityCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) == (int)Permission.Granted)
            {
                var path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
                var file = new File(path, "myfile.pdf");
                var theByteArray = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };

                using (var output = new FileOutputStream(file))
                {
                    try
                    {
                        await output.WriteAsync(theByteArray);
                    }
                    catch (Exception ex)
                    {

                    }
                }

            }

        };


    }
    /**
* Root of the layout of this Activity.
*/
    View layout;
    void RequestContactsPermissions()
    {
        if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.ReadContacts)
            || ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.WriteContacts))
        {

            // Provide an additional rationale to the user if the permission was not granted
            // and the user would benefit from additional context for the use of the permission.
            // For example, if the request has been denied previously.
            Log.Info(TAG, "Displaying contacts permission rationale to provide additional context.");

            // Display a SnackBar with an explanation and a button to trigger the request.
            Snackbar.Make(layout, "Storage Permission is needed",
                Snackbar.LengthIndefinite).SetAction("OK", new Action<View>(delegate (View obj)
                {
                    ActivityCompat.RequestPermissions(this, PERMISSIONS_STORAGES, REQUEST_STORAGES);
                })).Show();
        }
        else
        {
            //  permissions have not been granted yet. Request them directly.
            ActivityCompat.RequestPermissions(this, PERMISSIONS_STORAGES, REQUEST_STORAGES);
        }
    }
    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
    {
        if (requestCode == REQUEST_STORAGES)
        {
            // Received permission result for  permission.
            Log.Info(TAG, "Received response for Storage permission request.");

            // Check if the only required permission has been granted
            if ((grantResults.Length == 1) && (grantResults[0] == Permission.Granted))
            {
                Log.Info(TAG, "Storage permission has now been granted.");
            }
            else
            {
                Log.Info(TAG, "Storage permission was NOT granted.");
            }
        }
        else
        {
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

введите описание изображения здесь

...