问题描述
我正在尝试将文件导出到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
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)