首页 > 解决方案 > System.UnauthorizedAccessException:访问路径被拒绝-Xamarin

问题描述

我有 PDF 文件要阅读,但出现异常

System.UnauthorizedAccessException:对路径“/storage/emulated/0/geometry.pdf”的访问被拒绝。

Downloadbtn_click下面的方法

if (ContextCompat.CheckSelfPermission(this.Context, Manifest.Permission.ReadExternalStorage) != Permission.Granted)
{
   ActivityCompat.RequestPermissions(this.Activity, new String[] { Manifest.Permission.ReadExternalStorage }, 1);
}
else
{
    var externalPath = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/" + fileName;
    //Below line getting exception
    System.IO.File.WriteAllBytes(externalPath, PdfBytes);
    var pdfPath = Android.Net.Uri.FromFile(new Java.IO.File(externalPath));
    Intent intent = new Intent(this.Activity.Intent.Action);
    intent.SetDataAndType(pdfPath, "application/pdf");
    this.Context.StartActivity(intent);
}

覆盖OnRequestPermissionsResult方法

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
{
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
    case 1:
    {
        if (grantResults.Length > 0&& grantResults[0] == Permission.Granted)
        {
            var externalPath = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/" + fileName;
            System.IO.File.WriteAllBytes(externalPath, bt);
            var pdfPath = Android.Net.Uri.FromFile(new Java.IO.File(externalPath));
            Intent intent = new Intent(this.Activity.Intent.Action);
            this.Context.StartActivity(intent);
        }
        return;
    }
}
}

清单文件

<uses-sdk android:minSdkVersion="17" android:targetSdkVersion="27" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

方法OnRequestPermissionsResult永远不会被调用。单击下载按钮时,控件将直接else作为Menifest.xml文件中已提供的权限进行部分处理。

例外情况

System.IO.File.WriteAllBytes(externalPath, PdfBytes);

我该如何解决这个恼人的问题。

标签: c#androidxamarinxamarin.android

解决方案


欢迎使用 Android 8。我也遇到了这个问题。

事实证明 ReadExternalStorage 已经不够用了。如果您转到应用程序设置,您将看到没有读取或写入设置,只有文件访问权限。要解决问题,请求读取和写入权限并同时检查它们:

{ Manifest.Permission.ReadExternalStorage, Manifest.Permission.WriteExternalStorage }

不就是写作吗?System.IO.File.WriteAllBytes(externalPath, PdfBytes);

根据文档,它应该适用于阅读,但实际上它对我不起作用。

根据文档

权限

在 Android 8.0(API 级别 26)之前,如果应用程序在运行时请求权限并且权限被授予,系统也会错误地授予该应用程序属于同一权限组的其余权限,并且在显现。

对于面向 Android 8.0 的应用,此行为已得到纠正。该应用程序仅被授予其明确请求的权限。但是,一旦用户授予应用程序权限,该权限组中的所有后续权限请求都会自动授予。

例如,假设一个应用在其清单中同时列出了 READ_EXTERNAL_STORAGE 和 WRITE_EXTERNAL_STORAGE。应用程序请求 READ_EXTERNAL_STORAGE 并且用户授予它。如果应用针对 API 级别 25 或更低,系统也会同时授予 WRITE_EXTERNAL_STORAGE,因为它属于同一个 STORAGE 权限组,并且也在清单中注册。如果应用面向 Android 8.0(API 级别 26),系统此时仅授予 READ_EXTERNAL_STORAGE;但是,如果应用程序稍后请求 WRITE_EXTERNAL_STORAGE,系统会立即授予该权限而不提示用户。


推荐阅读