簡體   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