nino
nino

Reputation: 491

Restore sqlite database in c#

I programmed a c# application that can work on any other computer so i used from sqlite database.I want to backup and restore data in this app.for backup it's ok.I use from below code:

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);
    }
}

But i dont know about restore.how can i restore the database wichi backuped? I searche alot but no result.

Upvotes: 3

Views: 3277

Answers (2)

Mamad
Mamad

Reputation: 454

For restore just use something like this :

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

Upvotes: 2

Usama
Usama

Reputation: 77

Try this 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");
    }
}

Upvotes: 3

Related Questions