System.UnauthorizedAccessException:访问路径被拒绝-Xamarin

时间:2018-09-26 09:43:36

标签: c# android xamarin xamarin.android

我有要阅读的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);

我该如何解决这个令人讨厌的问题。

1 个答案:

答案 0 :(得分:1)

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

结果证明,ReadExternalStorage不再足够。如果您转到应用程序设置,则会看到没有读取或写入设置,只有文件访问权限。要解决该问题,请同时请求读写权限,并同时检查它们:

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

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

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

根据docs

  

权限

     

在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,则   系统会立即授予该特权,而不会提示用户。