首页 文章

用户无法从UWP App中选择SQLite数据库位置

提问于
浏览
2

使用Preserve access to a StorageFolder中的代码Preserve access to a StorageFolder

public static async Task<StorageFolder> GetOrPickAndRememberFolderAsync(string key)
{
    if (StorageApplicationPermissions.FutureAccessList.ContainsItem(key))
    {
        return await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(key);
    }
    var picker = new FolderPicker();
    picker.FileTypeFilter.Add("*");
    StorageFolder folder = await picker.PickSingleFolderAsync();
    if (folder != null)
    {
        StorageApplicationPermissions.FutureAccessList.AddOrReplace(key, folder);
    }
    return folder;
}

我们的UWP应用程序能够浏览并记住用户选择的SQLite数据库的位置 . 这应该给该文件夹的读/写权限 .

dbContext像这样实例化

public dbContext(string dbPath)
    {
        databasePath = dbPath;
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Filename=" + databasePath);
    }

如果用户选择应用程序的默认本地存储位置,则此代码有效 .

var picker = new FolderPicker();
        picker.FileTypeFilter.Add("*");
        StorageFolder folder = await picker.PickSingleFolderAsync();

        StorageFolder dbFolder = await GetOrPickAndRememberFolderAsync("LocalDbFolder");
        string dbPath = Path.Combine(dbFolder.Path, "MySQLite.db");

        using (var db = new dbContext(dbPath))
        {
            db.Database.Migrate();
        }

但是,如果用户选择任何其他位置(例如其“文档”文件夹),则应用程序将失败并显示错误 "SQLite Error 14: 'unable to open database file'."

为什么会这样,因为用户通过选择器为应用程序提供了对所选位置的明确权限?

1 回答

  • 2

    你不能 . SQLite需要本机文件访问 . 要使用本机文件访问,应将sqlite .db文件放入应用程序本地文件夹--Windows.Storage.ApplicationData.Current.LocalFolder或tempfolder .

    如果使用文件/文件夹选择器,则可以获取存储文件夹项 . 但是,如果文件夹位于应用程序之外,则所有文件访问都是通过OS的代理进程完成的 . SQLite无法访问此类文件夹 .

相关问题