---
title: "Open a SQLite database read-only in C#"
url: https://recursiveai.org/onelite/cookbook/open-sqlite-database-read-only/
description: "Open an existing SQLite database read-only in C# using OneLite. Run a SELECT, handle SQLITE_READONLY on a write and check that the .db file is unchanged."
version: "1.0.0"
---

# Open a SQLite database read-only 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/open-sqlite-database-read-only/open-sqlite-database-read-only.zip)

The download creates `report.db`.

```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;
await using var db = await
    Database.OpenReadOnlyAsync("report.db");
Console.WriteLine(await db.ScalarAsync<string>(
    $"SELECT title FROM books"));
```

Unzip [the example](https://recursiveai.org/onelite/cookbook/open-sqlite-database-read-only/open-sqlite-database-read-only.zip), then `dotnet run`.

The snippet needs an existing `.db` file: use the example’s `report.db`, which contains `Dune`, or use your own file and adjust the `SELECT` to match its schema.

```text
Dune
```

## The full program

The download creates the example file only if it’s missing, then closes that setup connection before opening the existing file read-only. It reads the title, catches `SQLITE_READONLY` on an `UPDATE`, and compares the file bytes after closing. A read-only open on a missing local file throws `OneLiteException` with `SQLITE_CANTOPEN`.

```csharp
using RecursiveAI.OneLite;

const string path = "report.db";
if (!File.Exists(path))
{
    // Create a standalone fixture in rollback-journal mode.
    await using var setup = await Database.OpenAsync(path, new DatabaseOptions());
    await setup.ExecuteAsync($"CREATE TABLE books(title TEXT NOT NULL)");
    await setup.ExecuteAsync($"INSERT INTO books VALUES ({"Dune"})");
}

var before = File.ReadAllBytes(path);
await using (var db = await Database.OpenReadOnlyAsync(path))
{
    Console.WriteLine(await db.ScalarAsync<string>($"SELECT title FROM books"));
    try
    {
        await db.ExecuteAsync($"UPDATE books SET title = {"Changed"}");
        throw new InvalidOperationException("The write should have failed.");
    }
    catch (OneLiteException error) when (error.Code == ResultCode.ReadOnly)
    {
        Console.WriteLine($"SQLITE_READONLY ({error.Code}): {error.Message}");
    }
}

if (!before.AsSpan().SequenceEqual(File.ReadAllBytes(path)))
    throw new InvalidOperationException("The database file changed.");
Console.WriteLine("Database file unchanged.");
```

`dotnet run` prints:

```text
Dune
SQLITE_READONLY (8): attempt to write a readonly database
Database file unchanged.
```

## Variations

**Handle a missing file.** A read-only open reports `SQLITE_CANTOPEN` instead of creating a database.

```csharp
using RecursiveAI.OneLite;

var path = $"missing-{Guid.NewGuid():N}.db";
try
{
    await using var db =
        await Database.OpenReadOnlyAsync(path);
}
catch (OneLiteException error)
    when (error.Code == ResultCode.CantOpen)
{
    Console.WriteLine($"SQLITE_CANTOPEN ({error.Code})");
    Console.WriteLine(error.Message);
}
```

```text
SQLITE_CANTOPEN (14)
unable to open database file
```

## Related recipes

[Open an existing file](https://recursiveai.org/onelite/cookbook/open-existing-sqlite-database-csharp/) · [Create a SQLite database](https://recursiveai.org/onelite/cookbook/create-sqlite-database-csharp/) · [Read a database over HTTP](https://recursiveai.org/onelite/cookbook/read-sqlite-database-over-http-csharp/)

---

## The short answer

Call `Database.OpenReadOnlyAsync(path)` on an existing SQLite file, then use the normal OneLite query methods. You don’t need to change file permissions or build a connection string for the core API. A write through that connection fails with `SQLITE_READONLY`. Unlike the default `OpenAsync`, the read-only open does not switch the file to write-ahead logging (WAL).

If you use `SqliteConnection` with OneLite’s [SQLitePCLRaw adapter](https://recursiveai.org/onelite/docs/adapter/), add `Mode=ReadOnly` to the connection string to open an existing file without allowing writes.

## Can I open an existing SQLite database in read-only mode?

Yes. Give `OpenReadOnlyAsync` the path to an existing file and wait for the open before issuing a query. A relative path is resolved from the program’s working directory. If you get `SQLITE_CANTOPEN`, check that the path points to the database you intended to read and that your process can access it. Unlike a read-write create call, the read-only open won’t silently make an empty database at a misspelled path.

Use this mode for reports, inspection tools, and readers that don’t need to create tables. Read-only applies to the connection you opened. It doesn’t change the file’s permissions or prevent another process with write access from opening and changing it. The byte comparison in the download checks what happened to one local fixture; it’s not a lock on the file or a guarantee that other processes won’t change it.

## What does “attempt to write a readonly database” mean?

The error means a write was attempted through a connection that can’t write to the database. In the example that’s intentional: `SELECT` returns `Dune`, but the `UPDATE` fails with `SQLITE_READONLY` (8). OneLite reports it as `OneLiteException`. The exception filter checks the result code, so an unrelated error such as a missing table is not mistaken for a successful read-only check.

If you only wanted to read the file, remove the statement that writes, rather than reopening the database with extra privileges. Creating a table or running a migration is a write too, so keep database setup separate from the report or inspection code. If the error happens on a `SELECT`, check the file’s journal state. For example, a rollback journal left by an interrupted write may need recovery before a read can proceed. A read-only connection can’t do that recovery. A database already in WAL mode may also need a writable directory when its sidecar files are missing. See the [file and journal cases](https://recursiveai.org/onelite/docs/engine/#opening-and-locking) before treating a live database as a standalone `.db` file.
