如何在另一个应用程序中打开由一个 Xamarin Android 应用程序创建的 SQLite 数据库?

How to open SQLite DB created by one Xamarin Android app in another app?

我有一个创建 SQLite 数据库的 Xamarin Android 应用程序。重新安装此应用程序后,我无法使用新版本的应用程序打开数据库。出于测试目的,数据库文件位于下载文件夹中。 当应用程序刚刚更新而不是重新安装时,它会正常访问数据库。

一个动机:获得一个独立的数据库文件,可以在将应用程序移动到另一个设备时用作备份。

编辑:

App.xaml.cs:

public partial class App : Application
{
    private readonly static string _dirPath = "/storage/emulated/0/Download/InventoryApp";
    private static InvDB _database;            
    public static InvDB Database
    {
        get
        {
            if (_database == null)
            {
                string dbFileName = "InventoryDB.db3";
                _database = new InvDB(Path.Combine(_dirPath, dbFileName));
            }
            return _database;
        }

    }
    // ....
}

数据库class构造函数:

public class InvDB
{
    readonly SQLiteAsyncConnection conn;

    public const SQLite.SQLiteOpenFlags Flags =        
    SQLite.SQLiteOpenFlags.ReadWrite |
    SQLite.SQLiteOpenFlags.Create |
    SQLite.SQLiteOpenFlags.FullMutex;

    public InvDB(string dbPath)
    {
        if(File.Exists(dbPath))
        {
            conn = new SQLiteAsyncConnection(dbPath, Flags);
            conn.CreateTableAsync<Item>().Wait();
            conn.CreateTableAsync<Room>().Wait();
        }
    }
    // ....
}

一开始,READ_EXTERNAL_STORAGE、WRITE_EXTERNAL_STORAGE权限需要用户自己授予,所以你不仅需要将它们添加到manifest文件中,还需要做一个权限请求获得许可。

你可以检查这个link:

如果还是不行,您可以尝试授予应用程序访问所有文件的权限,但我不建议这样做。

你可以查看我几个月前发布的答案:How to Request manage_external_storage Permission in Xamarin.Android

更新:

看来Download文件夹比较特殊,我在里面新建了一个txt文件,尝试用write external storage权限写入。但是我失败了,官方文档说:

If your app wants to access a file within the MediaStore.Downloads collection that your app didn't create, you must use the Storage Access Framework. To learn more about how to use this framework, see the guide on how to access documents and other files.

可以查看官方文档:https://developer.android.com/training/data-storage/shared/media#scoped_storage_enabled

然后我将 <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" /> 添加到清单文件中,并使用我上面提供的 link 中的代码来请求 MANAGE_EXTERNAL_STORAGE 权限。我写文件成功了。

所以你也可以尝试这样做或者use the Storage Access Framework就像官方文档说的那样打开下载文件夹中的数据库文件