Litedb: Can it run in memory?

Created on 25 Nov 2016  路  3Comments  路  Source: mbdavid/LiteDB

I mean, when the app begins, LiteDB can load all data into memory, and then LiteDB synchronizes with the local file when the collection change.
Maybe it's not necessary, I only ask a question.

question

Most helpful comment

Please note that you have to open the memory stream this way, in order to be expandable:

```c#
using (var ms = new MemoryStream())
{
// Do your thing, for example:
m.Attachments[0].ContentStream.CopyTo(ms);

return ms.ToArray(); // This gives you the byte array you want.

}


I.e. you have to call the parameter-less c'tor of `MemoryStream` and later insert the file content into this stream.

----

To catch on to the above example of mbdavid, I've written this function:

```c#
private static MemoryStream readStream(string path)
{
    using (var temp = new MemoryStream(File.ReadAllBytes(path)))
    {
        var ms = new MemoryStream();
        temp.CopyTo(ms);

        return ms;
    }
}

Then, I inserted a call to this function in the example like:

```c#
using (var mem = readStream("data.db"))
{
using (var db = new LiteDatabase(mem))
{
// here, all database are in memory only
}

File.WriteAllBytes("data.db", mem.ToArray());

}
```

(Please note that I've put the memory stream into a using block, too.

All 3 comments

Yes it's possible. You can load you file to memory and initialize LiteDB using MemoryStream and when you want persist in disk, write from memory to disk. some like this:
```
var mem = new MemoryStream(File.ReadAllBytes("data.db"));

using (var db = new LiteDatabase(mem))
{
// here, all database are in memory only
}

File.WriteAllBytes("data.db", mem.ToArray());

Good.

Please note that you have to open the memory stream this way, in order to be expandable:

```c#
using (var ms = new MemoryStream())
{
// Do your thing, for example:
m.Attachments[0].ContentStream.CopyTo(ms);

return ms.ToArray(); // This gives you the byte array you want.

}


I.e. you have to call the parameter-less c'tor of `MemoryStream` and later insert the file content into this stream.

----

To catch on to the above example of mbdavid, I've written this function:

```c#
private static MemoryStream readStream(string path)
{
    using (var temp = new MemoryStream(File.ReadAllBytes(path)))
    {
        var ms = new MemoryStream();
        temp.CopyTo(ms);

        return ms;
    }
}

Then, I inserted a call to this function in the example like:

```c#
using (var mem = readStream("data.db"))
{
using (var db = new LiteDatabase(mem))
{
// here, all database are in memory only
}

File.WriteAllBytes("data.db", mem.ToArray());

}
```

(Please note that I've put the memory stream into a using block, too.

Was this page helpful?
0 / 5 - 0 ratings