如何解决Xamarin:使用API级别> = 29
我正在尝试将文件导出到Xamarin中Android手机的公共外部存储中,以用于备份数据库。但是,在最新版本的Android手机(11.0 - API30
)中,无法使用android:requestLegacyExternalStorage="true"
中<application>
标签的属性manifest.xml
退出作用域存储
在创建文件之前,我确保已授予权限READ_EXTERNAL_STORAGE
和WRITE_EXTERNAL_STORAGE
。不过,在尝试创建文件时,会抛出System.UnauthorizedAccessException
异常。
/* file 1: */
// ....
private async void Export_Tapped (object sender,EventArgs e) {
// check if permission for writing in external storage is given
bool canWrite = await FileSystem.ExternalStoragePermission_IsGranted ();
if (!canWrite) {
// request permission
canWrite = await FileSystem.ExternalStoragePermission_Request ();
if (!canWrite) {
// alert user
return;
}
}
// find the directory to export the db to,based on the platform
string fileName = "backup-" + DateTime.Now.ToString ("yyMMddThh:mm:ss") + ".db3";
string directory = FileSystem.GetDirectoryForDatabaseExport (); // returns "/storage/emulated/0/Download"
string fullPath = Path.Combine (directory,fileName);
// copy db to the directory
bool copied = false;
if (directory != null)
copied = DBConnection.copyDatabase (fullPath);
if (copied)
// alert user
else
// alert user
}
// ....
/* file 2: */
class DBConnection
{
private readonly string dbPath;
// ....
public bool copyDatabase(string path)
{
byte[] dbFile = File.ReadAllBytes(dbPath);
File.WriteallBytes(path,dbFile); // --> this is where the exception is thrown <--
return true;
}
// ....
}
问题就来了:如何将新文件写入API级为29或更高的Android设备的公共外部存储?
到目前为止我发现的所有资源,也许您可以收集比我更多的信息:
- https://forums.xamarin.com/discussion/179999/access-denied-to-external-storage
- (关于私有外部存储)https://forums.xamarin.com/discussion/171039/saving-files-to-external-storage
- https://docs.microsoft.com/en-us/xamarin/android/platform/files/external-storage?tabs=windows
- https://developer.android.com/about/versions/11/privacy/storage#permissions
解决方法
尝试此操作,我使用dependency service在Native Android中调用此方法,并按字节数组保存docx和pdf等文件。
public async Task<bool> CreateFile(string fileName,byte[] docBytes,string fileType)
{
try
{
Java.IO.File file = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath,fileName + fileType);
OutputStream os = new FileOutputStream(file);
os.Write(docBytes);
os.Close();
}
catch
{
return false;
}
return true;
}
,
您使用的路径不正确,请尝试以下文件路径。
Context context = Android.App.Application.Context;
var filePath = context.GetExternalFilesDir(Android.OS.Environment.DirectoryDocuments);
请参阅https://forums.xamarin.com/discussion/comment/422501/#Comment_422501。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。