Xamarin:使用API​​级别> = 29

问题描述

我正在尝试将文件导出到Xamarin中Android手机的公共外部存储中,以用于备份数据库。但是,在最新版本的Android手机(11.0 - API30)中,无法使用android:requestLegacyExternalStorage="true"<application>标签的属性manifest.xml退出作用域存储

在创建文件之前,我确保已授予权限READ_EXTERNAL_STORAGEWRITE_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设备的公共外部存储?


到目前为止我发现的所有资源,也许您可​​以收集比我更多的信息:

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)