0

序幕:

我正在为 UWP 编写 SQLite GUI 客户端。我使用Microsoft.Data.SqliteC# 的 SQLite API 库。我还使用重定向表来打开我在 Microsoft Store 中发布的沙盒应用程序中的数据库。重定向表替换CreateFileWCreateFileFromAppW调用和类似的。

问题:

用户具有File->Save as功能。当用户创建一个新的数据库文件时,会在应用程序本地目录中创建一个。接下来当用户保存他/她的数据库时我需要移动这个文件。我使用StorageFileAPI 因为我不能在沙盒应用程序中使用任何其他文件 API。所以我打电话:

var savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
savePicker.FileTypeChoices.Add("SQLite3 Database", new List<string>() { ".sqlite", ".db" });
savePicker.SuggestedFileName = "Database";
var file = await savePicker.PickSaveFileAsync();
if(null != file)
{                    
    Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file);
    sqliteConnection.Close();  // it is important cause if I skip this moving a file will fail
    var localFolder = ApplicationData.Current.LocalFolder;
    var currentStorageFile = await localFolder.GetFileAsync(App.UnsavedDatabaseFileName);  // here I obtain StorageFile for opened database
    await currentStorageFile.MoveAndReplaceAsync(file);  // here I move a file
    sqliteConnection = new SqliteConnection("Data Source=" + file.Path);
    sqliteConnection.Open();  // this line fails with error 14: cannot open database file
}            

我还尝试跳过关闭并重新打开连接->然后移动文件失败。如果我FileOpenPicker在两者之间调用await currentStorageFile.MoveAndReplaceAsync(file);sqliteConnection = new SqliteConnection("Data Source=" + file.Path);那么一切都会正常工作,但是在文件保存选择器之后立即显示文件打开选择器是非常糟糕的用户体验。我知道沙盒应用程序仅在用户手动选择文件后才授予文件访问权限。但看起来这FileSavePicker并没有像我一样给我许可FileOpenPicker。我找不到任何有关它的信息。

结语:

这是应用程序https://sqliteman.dev。请随时批评,因为它使我的应用程序变得更好。

4

3 回答 3

0

尝试放入MoveAndReplaceAsync()using 语句,并在其外部打开 SQLite 连接。

于 2021-06-12T17:26:17.597 回答
0

如果是权限问题,那么一种解决方案是在应用程序的清单中声明 broadFileSystemAccess。

https://docs.microsoft.com/en-us/windows/uwp/files/file-access-permissions

我觉得奇怪的是您没有对您创建的文件的写入权限。

于 2021-06-12T17:10:26.847 回答
0

更新:

我已经测试了 broadFileSystemAccess 功能,它不起作用并且仍然报告异常“无法打开数据库文件”。因此,使用 broadFileSystemAccess 功能是不可行的。

如果你想在 uwp 中使用 Sqlite,只有两个位置可以访问。ApplicationData 和 Application 安装目录,区别在于 ApplicationInstallation 只能读取,ApplicationData 可以读写。因此,当您连接位于另一个位置的文件时,它会报告异常。

我的意思是你可以将数据库文件存储在任何地方,但是当你操作这个数据库文件时,你需要把这个文件移动到可以访问的位置。(ApplicationData,Application安装目录)。否则,无法将数据插入到数据库文件的表中,甚至无法连接数据库文件。

于 2021-06-14T02:12:28.060 回答