使用 StorageFile 参数创建 LiteDb 数据库

Creating a LiteDb database with a StorageFile argument

我正在尝试使用 UWP 在我的 raspberry pi 上使用 LiteDb 实现数据库提供程序。它有一个连接的外部硬盘驱动器,我非常想将它用作特定的 "Database" 驱动器,以允许我拥有更大的支持数据库大小。

我收到一个 StorageFile,然后将用作我的数据库文件。 LiteDb 上的一个构造函数使用一个流 (System.IO.Stream),无论如何将 StorageFile 对象转换为一个流(派生自 System.IO.Stream)以满足新的 win10 安全限制(需要访问区域等的用户权限,防止传统的文件。Write/path 基于对应用程序数据目录以外的任何内容的访问。

真的卡住了,我试过的选项是:

var stream = storageProvider.StorageLocaton.OpenAsync(FileAccessMode.ReadWrite);

不幸的是,我找不到任何其他方法可以 read/write 以流的形式访问文件。

希望这里有人有作品around/solution。

...is there anyway to convert the StorageFile object into a stream...

您可以使用 StorageFile.OpenAsync(FileAccessMode.ReadWrite) 进行写作,StorageFile.OpenAsync(FileAccessMode.Read) 进行阅读。

至于

win10 security restrictions (requiring user permissions to access areas etc., preventing traditional File.Write/path based access to anything other than your application data directory).

您可以利用 PublisherCacheFolder:

The strong security model of Windows Runtime app typically prevents apps from sharing data among themselves. It can be useful, however, for apps from the same publisher to share files and settings on a per-user basis. As an app publisher, you can register your app to share a storage folder with other apps that you publish by adding extensions to the app manifest.

以下代码片段您可以参考:

        StorageFolder sharedFonts = Windows.Storage.ApplicationData.Current.GetPublisherCacheFolder("test");
        var testFile = await sharedFonts.CreateFileAsync("test.txt", CreationCollisionOption.OpenIfExists);

        var byteArray = new byte[] { 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a };
        using (var sourceStream = new MemoryStream(byteArray).AsRandomAccessStream())
        {
            using (var destinationStream = (await testFile.OpenAsync(FileAccessMode.ReadWrite)).GetOutputStreamAt(0))
            {
                await RandomAccessStream.CopyAndCloseAsync(sourceStream, destinationStream);
            }
        }

        var readArray = new byte[100];
        using (var destinationStream = new MemoryStream(readArray).AsRandomAccessStream())
        {
            using (var sourceStream = (await testFile.OpenAsync(FileAccessMode.Read)).GetInputStreamAt(0))
            {
                await RandomAccessStream.CopyAndCloseAsync(sourceStream, destinationStream);
            }
        }

更新:

您可以像这样将 IRandomAccessStream 转换为 System.IO.Stream

Stream writeStream = destinationStream.AsStreamForWrite();

Stream readStream = sourceStream.AsStreamForRead();