For a game's save file, a desktop application's project file or an offline cache, SQLite offers single-file, transactional storage. In .NET, Microsoft.Data.Sqlite exposes the engine through ADO.NET. This article stores a document as one SQLite file and walks through how connection pooling affects file locks, atomic replacement through a temp file, schema versions with PRAGMA user_version and integrity checks, with examples.
One SQLite file per document
When SQLite is used as an application file format, the document is one file that holds several tables, transactions and SQL queries. Keeping one file per save slot turns backup, copy and delete into ordinary file operations. Only the needed part of a large document has to be read; unlike JSON, the whole file does not have to be loaded into memory.
Rules such as value ranges can be protected in the database too with CHECK constraints, so an application bug cannot write an invalid record to disk. Values are never concatenated into SQL text. Microsoft.Data.Sqlite accepts $name, @name and :name parameter names; a parameterized command is both safe and reusable.
SQLite — As an application file format
Connection pooling and file locks
Since version 6.0, Microsoft.Data.Sqlite pools connections by default. A disposed connection stays open in the background, waiting to be reused. If the application then immediately tries to move, delete or replace the same file, Windows reports that the file is in use by another process.
For short-lived databases whose files the application manages itself, Pooling=False is the simplest fix: Dispose really closes the file handle. The alternative is calling SqliteConnection.ClearPool or ClearAllPools. Use Mode=ReadOnly for read-only access; in that mode a missing file is not created. Building the connection string with SqliteConnectionStringBuilder keeps special characters in the path from breaking it.
Microsoft Learn — Microsoft.Data.Sqlite connection strings
A temp file and atomic replacement
SQLite transactions prevent half-finished writes inside a file. If the whole document is rewritten on every save, there is an even simpler shape: write the new content to a temp file in the same folder, and once the transaction has committed and the connection is closed, put it in place with File.Replace and keep the old version as .bak. If power fails during the write, the old file stays intact.
File.Replace expects the destination to exist, so the first save uses File.Move. The method fails when source and destination are on different volumes, which is why the temp file is created next to the target. The default journal mode leaves a single file once the transaction finishes; if WAL mode is enabled, the -wal and -shm side files must be taken into account.
using Microsoft.Data.Sqlite;
public static class SaveFile
{
public static SqliteConnection Open(string path, bool readOnly) =>
new(new SqliteConnectionStringBuilder
{
DataSource = path,
Mode = readOnly ? SqliteOpenMode.ReadOnly : SqliteOpenMode.ReadWriteCreate,
Pooling = false, // Dispose really closes the file handle
}.ToString());
public static void Save(string target, Action<SqliteConnection, SqliteTransaction> write)
{
string temp = target + ".tmp"; // same folder, same volume
File.Delete(temp);
using (var db = Open(temp, readOnly: false))
{
db.Open();
Migrations.Apply(db);
using var tx = db.BeginTransaction();
write(db, tx);
tx.Commit();
} // closed: the file is no longer locked
if (File.Exists(target))
File.Replace(temp, target, target + ".bak", ignoreMetadataErrors: true);
else
File.Move(temp, target);
}
}Microsoft Learn — File.Replace
Schema migrations with PRAGMA user_version
user_version is an integer in the database header reserved for the application; SQLite itself does not use it. Reading it as the schema version, applying the missing steps in order and bumping the version with each step gives a simple but solid migration system. DDL in SQLite is transactional; if a step fails, both the table changes and the version number roll back.
Published steps are never edited; a fix is added as a new step. Adding a NOT NULL column with ALTER TABLE ADD COLUMN requires a non-NULL default value. If the file uses a newer schema than the application knows, it is not opened and a clear error is shown instead. A copy taken before migrating leaves a way back from a faulty release.
public static class Migrations
{
private static readonly string[] Steps =
[
// version 1
"""
CREATE TABLE Meta (Key TEXT PRIMARY KEY, Value TEXT NOT NULL);
CREATE TABLE Unit (
Id INTEGER PRIMARY KEY,
Kind TEXT NOT NULL,
Health INTEGER NOT NULL CHECK (Health BETWEEN 0 AND 1000));
""",
// version 2: NOT NULL needs a default for existing rows
"ALTER TABLE Unit ADD COLUMN Stance TEXT NOT NULL DEFAULT 'normal';",
];
public static int Latest => Steps.Length;
public static void Apply(SqliteConnection db)
{
using var read = db.CreateCommand();
read.CommandText = "PRAGMA user_version;";
int current = Convert.ToInt32(read.ExecuteScalar());
if (current > Latest)
throw new InvalidDataException($"File schema {current} is newer than {Latest}.");
for (int version = current + 1; version <= Latest; version++)
{
using var tx = db.BeginTransaction();
using var step = db.CreateCommand();
step.Transaction = tx;
// PRAGMA takes no parameters; version is an integer we control.
step.CommandText = Steps[version - 1] + $"\nPRAGMA user_version = {version};";
step.ExecuteNonQuery();
tx.Commit();
}
}
}quick_check, checksums and falling back to the backup
PRAGMA integrity_check examines the structure of the file thoroughly. quick_check is faster because it skips UNIQUE constraints and the check that index content matches the table. Both return a single row containing ok when nothing is wrong. Run quick_check on load and integrity_check when the user starts a repair command.
SQLite catches structural corruption but knows nothing about application-level errors. If a canonical hash of the save content is stored in the Meta table, it can be recomputed and compared on load. When the main file cannot be opened or a check fails, try the .bak file. Show separate messages for file not found, corrupt, newer version and access denied.
Async methods, bulk inserts and the transaction object
SQLite does not support asynchronous I/O; the ADO.NET methods ending in Async run synchronously in Microsoft.Data.Sqlite, and the documentation recommends avoiding them. To keep the UI thread free, hand the whole save to the thread pool with Task.Run, and do not read scene or UI objects from that thread.
When inserting many rows, prepare one command once, change only the parameter values for each row, and run them all in a single transaction. Opening a transaction per row syncs to disk every time and is very slow. In Microsoft.Data.Sqlite, a command whose Transaction property is left unset joins the connection's open transaction; assigning a transaction from another connection, or one that has already completed, makes execution fail with InvalidOperationException. Setting the property explicitly also stays compatible with providers such as SqlClient, which require it.
public sealed record UnitRow(long Id, string Kind, int Health);
public static void WriteUnits(SqliteConnection db, SqliteTransaction tx, IEnumerable<UnitRow> units)
{
using var insert = db.CreateCommand();
insert.Transaction = tx; // explicit: checked against the connection
insert.CommandText = "INSERT INTO Unit (Id, Kind, Health) VALUES ($id, $kind, $health);";
var id = insert.Parameters.Add("$id", SqliteType.Integer);
var kind = insert.Parameters.Add("$kind", SqliteType.Text);
var health = insert.Parameters.Add("$health", SqliteType.Integer);
foreach (var unit in units) // one prepared statement, many rows
{
id.Value = unit.Id;
kind.Value = unit.Kind;
health.Value = unit.Health;
insert.ExecuteNonQuery();
}
}
// From UI code, the whole save runs on the thread pool:
// await Task.Run(() => SaveFile.Save(path, (db, tx) => WriteUnits(db, tx, snapshot.Units)));Microsoft Learn — Async limitations