在C#中恢复sqlite数据库

3

我编写了一个能够在任何计算机上运行的C#应用程序,因此我使用了SQLite数据库。我想备份和恢复此应用程序中的数据。备份方面已经没问题了。我使用以下代码:

private void button1_Click(object sender, EventArgs e)        
{   
using (var source = new SQLiteConnection("Data 
Source=bazarganidb.db;version=3"))
using (var destination = new SQLiteConnection("Data Source=" + textBox1.Text + "/" + DateTime.Now.ToString("yyyyMMdd") + "backup.db"))
    {
        source.Open();
        destination.Open();
        source.BackupDatabase(destination, "main", "main", -1, null, 0);
    }
}

但是我不知道如何进行恢复。我应该如何恢复备份的数据库?我已经搜索了很多,但没有结果。


您只需复制/移动备份文件,覆盖bazarganidb.db即可。 - Alex K.
谢谢您的关注。但是 SQLite 文件在 bin/Debug 文件夹中。我可以删除它并将新备份复制到其中吗? - nino
2个回答

3
尝试这段代码
class Program
{
    private static readonly string filePath = Environment.CurrentDirectory;

    static void Main(string[] args)
    {
       var filename = "bazarganidb.db";
       var bkupFilename = Path.GetFileNameWithoutExtension(filename) + ".bak";

       CreateDB(filePath, filename);

       BackupDB(filePath, filename, bkupFilename);
       RestoreDB(filePath, bkupFilename, filename, true);
    }

    private static void RestoreDB(string filePath, string srcFilename, string 
    destFileName, bool IsCopy = false)
    {
       var srcfile = Path.Combine(filePath, srcFilename);
       var destfile = Path.Combine(filePath, destFileName);

       if (File.Exists(destfile)) File.Delete(destfile);

       if (IsCopy)
          BackupDB(filePath, srcFilename, destFileName);
       else
          File.Move(srcfile, destfile);
    }

    private static void BackupDB(string filePath, string srcFilename, string 
    destFileName)
    {
       var srcfile = Path.Combine(filePath, srcFilename);
       var destfile = Path.Combine(filePath, destFileName);

       if (File.Exists(destfile)) File.Delete(destfile);

       File.Copy(srcfile, destfile);
    }

    private static void CreateDB(string filePath, string filename)
    {
       var fullfile = Path.Combine(filePath, filename);
       if (File.Exists(fullfile)) File.Delete(fullfile);

       File.WriteAllText(fullfile, "this is the dummy data");
    }
}

2
恢复时只需使用类似以下的内容:
  string BackupPath = "Backup/Backup.db";
  string restorePath = "Mydb.db";
  File.Copy(BackupPath, restorePath, true);
//copy has three parameters : string SourceFileName,string DesFileName,bool Overwrite 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接