如何将数据库保存到外部存储以便用户可以看到它?在 Xamarin 表单中

How to save db to external storage so user can see it? In Xamarin Forms

我想为用户生成一个数据库,以便他可以备份它。我想出了这个代码:

private async void ExportButton_Clicked(object sender, EventArgs e)
    {
        var dest = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        var filePath = System.IO.Path.Combine(dest, "SpotterBackup.db3");
        
        if (File.Exists(_dbPath))
        {
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            File.Copy(_dbPath, filePath);
        }
    }

但这只是写入内部存储,我已经搜索了一些解决方案,我刚刚找到了一些 java lang 解决方案。如何在 xamarin 中将数据库保存到外部存储?

您可以尝试使用以下代码将数据库文件复制到外部路径。我将 db 文件复制到下载文件夹。

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.IO;
using Notes.Droid;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;

[assembly: Dependency(typeof(GetDBFile1))]
namespace Notes.Droid
{

    class GetDBFile1 : ICopyDB
    {
        public void copy()
        {

            //  My Db orignal file path  string path1 = "/data/user/0/com.companyname.Notes/files/Notes3.db";
            string path = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "Notes3.db3");
          
            File f = new File(path);


            FileInputStream fis = null;
            FileOutputStream fos = null;

            fis = new FileInputStream(f);
          
         
            fos = new FileOutputStream("/storage/emulated/0/Download/databasename.db");
            while (true)
            {
                int i = fis.Read();
                if (i != -1)
                { fos.Write(i); }
                else
                { break; }
            }
            fos.Flush();

            Toast.MakeText(Android.App.Application.Context, "DB dump OK", ToastLength.Short).Show();


            fos.Close();
            fis.Close();
        }

    }
      
    }

并在 AndroidManifest.xml<application> 标签中添加 android:requestLegacyExternalStorage="true"

这里是运行ning截图。

注意:如果 运行 此代码在 android 11 或更高版本中,Google 不允许应用程序访问外部文件夹和 requestLegacyExternalStorage will be ignored

Apps that run on Android 11 but target Android 10 (API level 29) can still request the requestLegacyExternalStorage attribute. This flag allows apps to temporarily opt out of the changes associated with scoped storage, such as granting access to different directories and different types of media files. After you update your app to target Android 11, the system ignores the requestLegacyExternalStorage flag.

请参阅主题管理设备存储

Starting in Android 11, apps that use the scoped storage model can access only their own app-specific cache files. If your app needs to manage device storage

因此,在android 11 或更高版本(如iOS 的沙盒设计)中,我们无法将文件写入public 外部存储。