SQLite.Net 不会在 Win IoT 库中创建

SQLite.Net Won't Create In Win IoT Library

我一直在努力寻找一种在 Win IoT 下将 SQLite 数据库持久保存在 Pi 上的方法,该数据库可以被不同的后台应用程序访问(不能同时访问)。

当我发现库(音乐、图片、视频 - 但反常不是文档,无需更多工作)时,我以为我找到了答案。我可以在一个应用程序中创建一个文本文件并将其写入图片库的默认文件夹。然后我可以用另一个应用程序读取文本文件。 File.Exists returns 是的。宾果游戏(我想)!

但是,SQLite 不会在文件夹中创建数据库或打开我复制到文件夹中的现有数据库。 SQLite.Net.SQLiteConnection returns SQLite 异常:"Could not open database file: C:\Data\Users\DefaultAccount\Pictures\MyDb.db (CannotOpen)" - 没有进一步的线索。

该文件夹似乎授予完全权限。请问有人有什么想法吗?

正在创建和写入文本文件:

using System;
using Windows.ApplicationModel.Background;
using System.IO;
using System.Diagnostics;

//*** NOTE: Pictures Library checked in Package.appxmanifest 'Capabilities'

namespace LibraryTest
{
    public sealed class StartupTask : IBackgroundTask
    {
        private BackgroundTaskDeferral Deferral;

        public async void Run (IBackgroundTaskInstance taskInstance)
        {
            Deferral = taskInstance.GetDeferral ();

            var myPictures = await Windows.Storage.StorageLibrary.GetLibraryAsync
                (Windows.Storage.KnownLibraryId.Pictures);

            string path = myPictures.SaveFolder.Path;
            Debug.WriteLine ($"'Pictures' Folder: {path}");

            string newFilePath = Path.Combine (path, "TestTextFile.txt");
            Debug.WriteLine ($"New File Path: {newFilePath}");

            try {
                using ( var stream = File.OpenWrite (newFilePath) ) {
                    using ( var writer = new StreamWriter (stream) ) {
                        writer.Write ("This is some test text.");
                    }
                }
                Debug.WriteLine ($"File created OK");
            }
            catch (Exception ex) { Debug.WriteLine ($"Exception: {ex.Message}"); }
        }
    }
}

出品:

'Pictures' Folder: C:\Data\Users\DefaultAccount\Pictures
New File Path: C:\Data\Users\DefaultAccount\Pictures\TestTextFile.txt
File created OK

阅读:

using System;
using Windows.ApplicationModel.Background;
using System.IO;
using System.Diagnostics;

//*** NOTE: Pictures Library checked in Package.appxmanifest 'Capabilities'

namespace ReadLibraryTest
{
    public sealed class StartupTask : IBackgroundTask
    {
        private BackgroundTaskDeferral Deferral;

        public async void Run (IBackgroundTaskInstance taskInstance)
        {
            Deferral = taskInstance.GetDeferral ();

            var myPictures = await Windows.Storage.StorageLibrary.GetLibraryAsync
                (Windows.Storage.KnownLibraryId.Pictures);

            string path = myPictures.SaveFolder.Path;
            Debug.WriteLine ($"'Pictures' Folder: {path}");

            string newFilePath = Path.Combine (path, "TestTextFile.txt");
            Debug.WriteLine ($"New File Path: {newFilePath}");

            try {
                using ( var stream = File.OpenRead (newFilePath) ) {
                    using ( var reader = new StreamReader (stream) ) {
                        string fileContents = reader.ReadLine ();
                        Debug.WriteLine ($"First line of file: '{fileContents}'");
                    }
                }
                Debug.WriteLine ($"File read OK");
            }
            catch ( Exception ex ) { Debug.WriteLine ($"Exception: {ex.Message}"); }
        }
    }
}

出品:

'Pictures' Folder: C:\Data\Users\DefaultAccount\Pictures
New File Path: C:\Data\Users\DefaultAccount\Pictures\TestTextFile.txt
First line of file: 'This is some test text.'
File read OK

However, SQLite will not create a database in the folder or open an existing database that I copy to the folder. SQLite.Net.SQLiteConnection returns an SQLite exception: "Could not open database file: C:\Data\Users\DefaultAccount\Pictures\MyDb.db (CannotOpen)" - no further clues.

是的,我复现了这个问题。好像这个文件夹不支持SQLite文件操作,但我不知道问题出在哪里。

作为解决方法,您可以使用 PublisherCacheFolder。我创建 .db 文件并在一个后台应用程序中写入数据。并从另一个后台应用读取数据。有用。

联系人class:

public sealed class Contact
{
    public int Id { get; set; }
    public string Name { get; set; }
}

创建并写入文件:

            StorageFolder sharedFonts = Windows.Storage.ApplicationData.Current.GetPublisherCacheFolder("test");

            var sqlpath = System.IO.Path.Combine(sharedFonts.Path, "MyDb.db");

            using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), sqlpath))
            {
                conn.CreateTable<Contact>();
                for (var i = 0; i < 100; i++)
                {
                    Contact contact = new Contact()
                    {
                        Id = i,
                        Name = "A"
                    };
                    conn.Insert(contact);
                }
            }

读取文件:

            StorageFolder sharedFonts = Windows.Storage.ApplicationData.Current.GetPublisherCacheFolder("test");

            var sqlpath = System.IO.Path.Combine(sharedFonts.Path, "MyDb.db");

            using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), sqlpath))
            {
                var query = conn.Table<Contact>().Where(v => v.Name.Equals("A"));

                foreach (var stock in query)
                    Debug.WriteLine("contact: " + stock.Id);
            }

要使用此发布者文件夹,您需要在 Package.appxmanifest 中添加以下行:

  <Extensions>
    <Extension Category="windows.publisherCacheFolders">
      <PublisherCacheFolders>
        <Folder Name="test" />
      </PublisherCacheFolders>
    </Extension>
  </Extensions>

谢谢,丽塔。工作得很好。为了任何阅读者的利益,我正在使用 SqlLite 的异步版本并按如下方式创建连接:

const string FileName = "MyFile.db";
string DbDir;
string DbPath;


Constructor:
    DbDir = Windows.Storage.ApplicationData.Current.GetPublisherCacheFolder("test").Path;
    DbPath = Path.Combine (DbDir, DbFileName);


public SQLite.Net.Async.SQLiteAsyncConnection GetConnectionAsync ()
    {
        var connectionFactory = new Func<SQLite.Net.SQLiteConnectionWithLock>(()=>
                new SQLite.Net.SQLiteConnectionWithLock(new SQLitePlatformWinRT(),
                        new SQLite.Net.SQLiteConnectionString(DbPath, storeDateTimeAsTicks: false)));
        var asyncConnection = new SQLiteAsyncConnection(connectionFactory);
        return asyncConnection;
    }

然后,例如,读取 Parms 类型的 table:

public async Task<Parms> ReadParmsAsync ()
{
    var db = GetConnectionAsync ();
    var query = db.Table<Parms> ().Where (p => p.Id == 1);
    return await query.FirstOrDefaultAsync ();
}

我对 SQLite 异步连接的担心是它不是 IDisposable。因此,'factory' 最终会 运行 失去动力(内存,句柄)吗?但我想这是另一个话题的主题。