繁体   English   中英

在 C# 中,有没有办法将内存文件链接为内存 SQLite 数据库与 System.Data.SQLite?

[英]In C#, is there any way to have an in-memory file linked as an in-memory SQLite database with System.Data.SQLite?

我想做的是类似于以下内容:

using System.Data.SQLite;
using System.IO;

//My SQLite connection
SQLiteConnection myCon;

public void ReadAndOpenDB(string filename)
{
    FileStream fstrm = new FileStream(filename, FileMode.Open);
    byte[] buf = new byte[fstrm.Length];
    fstrm.Read(buf, 0, (int)fstrm.Length);
    MemoryStream mstrm = new MemoryStream(buf);

    //Do some things with the memory stream

    myCon = new SQLiteConnection(/*attach to my memory stream for reading*/);
    myCon.Open();

    //Do necessary DB operations
}

我不打算写入内存数据库,但在连接到它之前,我需要能够在我的程序中的 memory 中对文件做一些事情。

如果您不介意使用 Interop 并直接转到CreateFile() (然后将返回的 HANDLE 包装在 FileStream 中),您可以查看使用指定的 FILE_ATTRIBUTE_TEMPORARY 创建文件,只要有缓存 memory 可用,并在文件句柄关闭时自动删除文件。

如果有足够的缓存 memory 可用,指定 FILE_ATTRIBUTE_TEMPORARY 属性会导致文件系统避免将数据写回大容量存储,因为应用程序会在句柄关闭后删除临时文件。 在这种情况下,系统可以完全避免写入数据。 虽然它不像前面提到的标志那样直接控制数据缓存,但 FILE_ATTRIBUTE_TEMPORARY 属性确实告诉系统在不写入的情况下尽可能多地保存在系统缓存中,因此可能会引起某些应用程序的关注。

使用 Interop 和 CreateFile() 太复杂了。 这是创建具有 FILE_ATTRIBUTE_TEMPORARY 属性的文件的简单方法,它将尽可能使用缓存 memory:

var file = File.Create(path);
File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Temporary);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM