【问题标题】:Restore sqlite database in c#在 C# 中恢复 sqlite 数据库
【发布时间】:2017-11-04 16:42:47
【问题描述】:

我编写了一个可以在任何其他计算机上运行的 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 的备份文件
  • 感谢您的关注。但是 sqlite 文件位于 bin/Debug 文件夹中。我可以删除它并复制新的备份吗?

标签: c# sqlite restore


【解决方案1】:

试试这个code

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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-11
      相关资源
      最近更新 更多