我正在尝试将文件导出到 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