---
title: "Implement a SQLite virtual file system in C#"
url: https://recursiveai.org/onelite/cookbook/implement-sqlite-virtual-file-system/
description: "Wrap OneLite’s file VFS in C#, count database reads and delegate locking, sync and shared memory. Includes the complete wrapper and a runnable example."
version: "1.0.0"
---

# Implement a SQLite virtual file system in C#

**OneLite** is a free, open-source SQLite-compatible database for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneLite) · [GitHub](https://github.com/recursive-ai-oss/onelite-csharp) · [Docs](https://recursiveai.org/onelite/docs/) · [Download example (.zip)](https://recursiveai.org/onelite/cookbook/implement-sqlite-virtual-file-system/implement-sqlite-virtual-file-system.zip)

A virtual file system (VFS) supplies database file I/O and locking. This wrapper counts reads.

```shell
dotnet add package RecursiveAI.OneLite
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using RecursiveAI.OneLite;
using RecursiveAI.OneLite.Storage.Vfs;

// CountingVfs.cs is below; sample.db is in the download.
var vfs = new CountingVfs(FileVfs.Instance);
using var db = Database.Open("sample.db",
    new DatabaseOptions { Vfs = vfs });
using var connection = db.Connect();
using var query = connection.Prepare(
    "SELECT sum(value) FROM numbers");
int before = vfs.Reads;
if (query.Step())
    Console.WriteLine($"Sum: {query.GetInt64(0)}");
Console.WriteLine($"Reads: {vfs.Reads - before}");
```

```text
Sum: 60
Reads: 1
```

Unzip [the example](https://recursiveai.org/onelite/cookbook/implement-sqlite-virtual-file-system/implement-sqlite-virtual-file-system.zip), then `dotnet run`.

`sample.db` is included in the download and contains `numbers(value)` with values `10`, `20` and `30`. Add the `CountingVfs.cs` implementation below to the same project before running the snippet at the top. The full program also recreates these sample rows. File failures propagate from the delegated backend; the wrapper does not replace them with successful results. The read count can change with the query and which database pages are already cached in memory.

## The full program

```csharp
using RecursiveAI.OneLite;
using RecursiveAI.OneLite.Storage.Vfs;

using (var seed = Database.OpenDefault("sample.db"))
    seed.ExecuteScript("""
        CREATE TABLE IF NOT EXISTS numbers(value);
        DELETE FROM numbers;
        INSERT INTO numbers VALUES (10), (20), (30);
        """);

var vfs = new CountingVfs(FileVfs.Instance);
using var db = Database.Open("sample.db",
    new DatabaseOptions { Vfs = vfs });
using var connection = db.Connect();
using var query = connection.Prepare(
    "SELECT sum(value) FROM numbers");
int before = vfs.Reads;
if (query.Step())
    Console.WriteLine($"Sum: {query.GetInt64(0)}");
Console.WriteLine($"Reads: {vfs.Reads - before}");
```

`dotnet run` prints:

```text
Sum: 60
Reads: 1
```

The wrapper lives in `CountingVfs.cs`, included in the download:

```csharp
using RecursiveAI.OneLite.Storage.Vfs;

public sealed class CountingVfs(IVfs inner) : VfsBase
{
    public int Reads { get; private set; }
    public override string Name => "counting";
    // This wrapper implements synchronous I/O only.
    public override VfsCaps Caps =>
        (inner.Caps & ~VfsCaps.Async) | VfsCaps.Sync;
    public override int CurrentTimeMs => inner.CurrentTimeMs;
    public override string FullPathname(string path) =>
        inner.FullPathname(path);
    public override bool Access(string path, AccessMode mode) =>
        inner.Access(path, mode);
    public override void Delete(string path, bool syncDirectory) =>
        inner.Delete(path, syncDirectory);
    public override void Sleep(int ms) => inner.Sleep(ms);
    public override IVfsFile Open(string path, VfsOpenOptions flags) =>
        new CountingFile(inner.Open(path, flags), this);

    private sealed class CountingFile(IVfsFile file, CountingVfs owner)
        : VfsFileBase
    {
        public override VfsCaps Caps => owner.Caps;
        public override int SectorSize => file.SectorSize;
        public override DeviceCharacteristics Device => file.Device;
        public override IVfsShm? Shm => file.Shm;
        public override int Read(long offset, Span<byte> dst)
        {
            owner.Reads++;
            return file.Read(offset, dst);
        }
        public override void Write(long offset, ReadOnlySpan<byte> src) =>
            file.Write(offset, src);
        public override void WriteRun(long offset,
            ReadOnlySpan<ReadOnlyMemory<byte>> pages) =>
            file.WriteRun(offset, pages);
        public override void Sync(SyncMode mode) => file.Sync(mode);
        public override void SyncDirectory() => file.SyncDirectory();
        public override void Truncate(long size) => file.Truncate(size);
        public override long FileSize() => file.FileSize();
        public override bool Lock(LockLevel level) => file.Lock(level);
        public override void Unlock(LockLevel level) => file.Unlock(level);
        public override bool CheckReservedLock() => file.CheckReservedLock();
        public override void Dispose() => file.Dispose();
    }
}
```

## Variations

To use the async statement driver, add this after the first query. This wrapper is sync-only: its base class serves async reads inline, so this does not make the underlying file I/O nonblocking.

```csharp
using var asyncQuery = connection.Prepare(
    "SELECT count(*) FROM numbers");
if (await asyncQuery.StepAsync())
    Console.WriteLine(asyncQuery.GetInt64(0));
```

```text
3
```

## Related recipes

- [Read a database over HTTP](https://recursiveai.org/onelite/cookbook/read-sqlite-database-over-http-csharp/)
- [Join attached databases](https://recursiveai.org/onelite/cookbook/join-attached-sqlite-databases/)

## The short answer

Derive a wrapper from `VfsBase`, return wrapped `IVfsFile` objects from `Open`, and pass it as `DatabaseOptions.Vfs`. Increment the counter in the file’s `Read` method and delegate the real read. Preserve locking, synchronization, file identity and shared memory by forwarding those operations to the underlying backend.

The complete implementation above instruments an existing local-file backend. It is deliberately a synchronous wrapper, not an implementation of a new durable storage medium. OneLite’s [VFS documentation](https://recursiveai.org/onelite/docs/vfs/) describes the managed contracts; SQLite calls this kind of wrapper a [VFS shim](https://www.sqlite.org/vfs.html#vfs_shims).

## What is a virtual FS for a SQLite database?

The VFS sits below SQL execution and the pager. It names and opens files, reads and writes byte ranges, synchronizes storage and arbitrates locks. A virtual table changes how a SQL table gets its rows; a virtual file system changes how the database engine reaches storage.

OneLite exposes this layer as managed C# interfaces rather than requiring a native callback table. `IVfs` handles paths and file lifecycle. `IVfsFile` handles an open file, including byte reads, writes, length, locks and shared memory used to coordinate the write-ahead log (WAL). The example uses those public contracts from the core NuGet package.

`Reads: 1` counts calls made through the wrapper during `Step`, after the statement has been prepared. It is not a count of physical disk accesses. Some reads may be satisfied by operating-system caches, while some database pages may already be in the pager cache and never reach the VFS.

## How do I implement a custom SQLite virtual file system in C#?

Start with the two base classes if you need sync/async fallback behavior. This example implements the synchronous flavor of `VfsBase` and `VfsFileBase`. Its capability flags retain the underlying backend’s features except for native async support. The wrapper’s `Open` returns a `CountingFile` that owns the underlying file and disposes it when the engine is done.

The counter is shared by files opened through this wrapper, so it can include journal-file reads as well as database-file reads. The difference printed around the query isolates that interval. It still describes VFS calls, not SQL rows or pages returned to your application. Do not share this simple counter across concurrent workloads if you need independently attributable counts.

Use the full `CountingVfs.cs` implementation, not only an override of `Read`. File size, truncation, directory synchronization and shared memory all carry behavior the pager relies on. Forwarding the backend’s canonical path also preserves its file identity rules.

## Does a VFS wrapper preserve database locking and durability?

Only if it preserves the relevant operations and capabilities. This wrapper forwards `Lock`, `Unlock`, `CheckReservedLock`, `Sync`, `SyncDirectory` and `Shm`; it does not substitute no-op implementations. It also forwards sector size and device characteristics instead of inventing stronger guarantees.

For a genuinely new storage backend, those methods require a storage design, not placeholder returns. The contract treats locks as try-locks: failure returns immediately so the caller can run its busy policy. A short read returns the number of bytes actually read; the caller zero-fills the rest. Storage failures carry extended SQLite result codes in `VfsException`.

## Can a custom virtual file system use async I/O?

Yes. The contracts provide synchronous and asynchronous forms. A sync-only implementation serves async calls inline through the base classes, as the variation demonstrates. Awaiting that path does not stop synchronous storage operations from blocking the calling thread.

For an async-only backend, a synchronous call may block only when the backend declares `BlockingOk`. Otherwise it fails with MISUSE and the message “backend requires the async driver”. Choose capabilities that describe the implementation you actually supply, and use the async driver when the backend requires it.
