Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restore a SQL Server 2012 database .bak file in C#?

I have developed a MIS in Windows Forms in which I took backup of my SQL Server 2012 database, but I am unable to restore the backup (.bak) file.

This is my code:

private void buttonRestore_Click(object sender, EventArgs e)
{
    try
    {
        openFileDialog1.Filter = "Backup File |*.bak";

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string sql = "Alter Database BOQ SET SINGLE_USER WITH ROLLBACK IMMEDIATE;";
            sql += "Restore Database BOQ FROM DISK ='" + openFileDialog1.FileName + "' WITH REPLACE;";

            SqlConnection con = new SqlConnection("Data Source=.; Initial Catalog=BOQ;Integrated Security=True");
            SqlCommand command = new SqlCommand(sql,con);

            con.Open();
            command.ExecuteNonQuery();

            MessageBox.Show("Database Recovered Successfully!");
            con.Close();
            con.Dispose();
        }
    }
    catch (Exception ex) 
    { 
         MessageBox.Show(ex.Message); 
    }
}

But I get this error:

enter image description here

like image 411
Loyal Avatar asked Feb 18 '15 05:02

Loyal


1 Answers

You cannot connect to your database BOQ and then restore a .bak over top of it!

"Data Source=.; Initial Catalog=BOQ;Integrated Security=True"
                                ****

You need to connect to the master database, and then you can restore your BOQ database:

"Data Source=.; Initial Catalog=master;Integrated Security=True"
                                *******
like image 143
marc_s Avatar answered Sep 23 '22 01:09

marc_s