在c#中恢复sqlite数据库

时间:2017-11-04 16:42:48

标签: c# sqlite restore

我编写了一个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);
    }
}

但我不知道还原。我可以恢复数据库wichi backuped吗? 我搜索很多但没有结果。

2 个答案:

答案 0 :(得分:2)

尝试一下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");
    }
}

答案 1 :(得分:0)

要恢复,只需使用以下内容:

  string BackupPath = "Backup/Backup.db";
  string restorePath = "Mydb.db";
  File.Copy(BackupPath, restorePath, true);
//copy has three parameters : string SourceFileName,string DesFileName,bool Overwrite