shahid khan
shahid khan

Reputation: 439

How to restore back up programmatically

I created a backup on button click

My code for this is

con.Open();

string str = "USE [C:\\Users\\asus\\Documents\\Visual Studio 2012\\Projects\\bbcon_accout_software\\bb_con_accnt_soft_lib\\BbCon.mdf]";
string str1 = "BACKUP DATABASE [C:\\Users\\asus\\Documents\\Visual Studio 2012\\Projects\\bbcon_accout_software\\bb_con_accnt_soft_lib\\BbCon.mdf] TO DISK = 'C:\\Users\\Public\\aa.Bak' WITH FORMAT,MEDIANAME = 'Z_SQLServerBackups',NAME = 'Full Backup of Testdb';";

SqlCommand cmd1 = new SqlCommand(str, con);
SqlCommand cmd2 = new SqlCommand(str1, con);

cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();

MessageBox.Show("success");
con.Close();

Now I would like to restore the backed up database, please help I searched lots of questions, but I didn't get the answer I need - please help me to perform this task.

I tried to restore using this code:

string query = "RESTORE DATABASE BbCon FROM DISK='C:\\Users\\Public\\aa.Bak' WITH REPLACE";
con.Open();

using (SqlCommand cmd = new SqlCommand(query, con))
{
    cmd.ExecuteNonQuery();
}

con.Close();

but I am getting an error

enter image description here

Please help me with this

Upvotes: 2

Views: 1003

Answers (1)

Ben Thul
Ben Thul

Reputation: 32737

Each of the physical files needs to reside somewhere on the system that you're attempting to restore the backed up database to. The error message is telling you that the files are in use by another database. You can query sys.master_files to find out which database they belong to.

To resolve this, you need to either delete the database that is using those physical files or add a MOVE clause into your RESTORE statement. For the latter, it would look something like this:

RESTORE DATABASE BbCon FROM DISK='C:\\Users\\Public\\aa.Bak' WITH REPLACE,
move 'BBCon' to 'c:\temp\BBCon.mdf',
move 'BBCon_log' to 'c:\temp\BBCon_log.ldf';

Upvotes: 2

Related Questions