1

我正在尝试将文件导出到 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 设备的公共外部存储?


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

4

2 回答 2

0

试试这个,我使用依赖服务在 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;
        }
于 2020-10-09T19:12:37.343 回答
-1

您使用的路径不正确,请尝试以下文件路径。

Context context = Android.App.Application.Context;
var filePath = context.GetExternalFilesDir(Android.OS.Environment.DirectoryDocuments);

请参阅https://forums.xamarin.com/discussion/comment/422501/#Comment_422501

于 2020-10-01T07:41:56.277 回答