在c#中恢复sqlite数据库

问题描述 投票:1回答:1

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

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

c# sqlite restore
1个回答
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");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.