1

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?
HelloWorld
  • 3,381
  • 5
  • 32
  • 58
  • Possible duplicate of [How to backup sqlite database?](https://stackoverflow.com/questions/25675314/how-to-backup-sqlite-database) – Crowcoder Jan 19 '19 at 12:02
  • Just blindly copying an in-use database file is a great way to corrupt it or lose data. https://www.sqlite.org/backup.html discusses how to use the C API to safely backup an open db. – Shawn Jan 19 '19 at 15:24

1 Answers1

0

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);
urza.cc
  • 223
  • 1
  • 8