简体   繁体   中英

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

What I want to do is something along the lines of the following:

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
}

I do not plan on writing to the in-memory DB, but I need to be able to do some things with the file, in memory in my program, before connecting to it.

If you don't mind using Interop and going to CreateFile() directly (then wrapping the returned HANDLE in a FileStream) you could take a look at creating the file with FILE_ATTRIBUTE_TEMPORARY specified which will not write the file to disk as long as there is cache memory available and which will automatically delete the file when its handle is closed.

Specifying the FILE_ATTRIBUTE_TEMPORARY attribute causes file systems to avoid writing data back to mass storage if sufficient cache memory is available, because an application deletes a temporary file after a handle is closed. In that case, the system can entirely avoid writing the data. Although it does not directly control data caching in the same way as the previously mentioned flags, the FILE_ATTRIBUTE_TEMPORARY attribute does tell the system to hold as much as possible in the system cache without writing and therefore may be of concern for certain applications.

Using Interop and CreateFile() is too complex. Here is a simple way to create file with FILE_ATTRIBUTE_TEMPORARY attribute which will use cache memory as much as possible:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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