Xamarin Forms Android 中拒绝访问的 PDF 文件下载问题

问题描述

我在 Android 清单文件中有这些权限

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

也在运行时请求权限。

这是我的pdf下载代码

var documentsPath = (string)Android.OS.Environment.GetExternalStoragePublicDirectory("SHAZ");
string localPath = Path.Combine(documentsPath,filename);
File.WriteallBytes(localPath,bytes);

这是我从 android 应用程序中得到的。

** {System.UnauthorizedAccessException:访问路径“/storage/emulated/0/SHAZ/ABC.pdf”被拒绝。 在 System.IO.FileStream..ctor(System.String 路径,System.IO.FileMode 模式,System.IO.FileAccess 访问,System.IO.FileShare 共享,system.int32 bufferSize,System.Boolean 匿名,System.IO. FileOptions 选项)[0x001aa] 在 /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/corlib/System.IO/FileStream.cs:239 在 System.IO.FileStream..ctor(System.String 路径,System.IO.FileMode 模式,System.IO.FileAccess 访问,System.IO.FileShare 共享)[0x00000] 在 /Users/builder/jenkins/workspace/archive -mono/2020-02/android/release/mcs/class/corlib/System.IO/FileStream.cs:91 at (wrapper remoting-invoke-with-check) System.IO.FileStream..ctor(string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare) 在 System.IO.File.InternalWriteallBytes (System.String path,System.Byte[] bytes) [0x00000] 在 /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/ src/System.IO.FileSystem/src/System/IO/File.cs:429 在 System.IO.File.WriteallBytes (System.String path,System.Byte[] bytes) [0x00039] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/ src/System.IO.FileSystem/src/System/IO/File.cs:420 在 SHAZ_HR_Payroll.Droid.Models.SaveFile.SaveFiles(System.String 文件名,System.Byte[] 字节)[0x00034] 在 SaveFile.cs:25 在 SHAZ_HR_Payroll.Pages.Employee.EmployeeChangePasswrod.BtnDownload_Clicked (System.Object sender,System.EventArgs e) [0x000d7] 在 \XYZ.xaml.cs:84 } **

IDE:VS-2019 安卓版本:10 Xamarin 表单版本:5.0.0.1874

解决方法

如果面向 API 29+,即使您请求权限并且用户授予它,您也会收到错误,因为他们改变了存储的工作方式。

但如果您像我一样厌倦了 Android 每天让事情变得更加复杂,只需将 android:requestLegacyExternalStorage="true" 添加到您的清单 <application> 标记中,您就可以保存,直到您开始面向 API 30。