'Backing up SQLite .db file on ASP .NET Core web server

I'm running a .NET Core wep app. It uses Entity Framework for SQLite. Thus, a .db file is generated. From time to time I want to back up this .db file.

  • Can I do this reliably with File.Copy(...), or might that corrupt the file as other web requests might access it at the same time?
  • Should I use a mutex?


Solution 1:[1]

SQLite contains mechanism for "online backup". This way you can make backup of entire db file while the app/db is running:

The online backup API allows the contents of one database to be copied into another database file, replacing any original contents of the target database. The copy operation may be done incrementally, in which case the source database does not need to be locked for the duration of the copy, only for the brief periods of time when it is actually being read from. This allows other database users to continue without excessive delays while a backup of an online database is made. The effect of completing the backup call sequence is to make the destination a bit-wise identical copy of the source database as it was when the copying commenced. (The destination becomes a "snapshot.")

This is somewhat (only the non incremental version) exposed in Microsoft.Data.SQLite package. From MS docs:

// Create a full backup of the database
var backup = new SqliteConnection("Data Source=BackupSample.db");
connection.BackupDatabase(backup);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 urza.cc