Error :RESTORE cannot process database 'Test_DB' because it is in use by this session

Viewed 7705

Scenario :

I am working on C# windows form application with SQL Server 2008 R2 database server.all things are going well, even i am able to create data base backup but when i restore it pro-grammatically it give me error "RESTORE cannot process database 'Test_DB' because it is in use by this session. It is recommended that the master database be used when performing this operation. RESTORE DATABASE is terminating abnormally." here is my program for backup and restore

          //   back up code

        try
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.Filter = "SQL Server database backup files|*.bak";
            sd.Title = "Create Database Backup";


            if (sd.ShowDialog() == DialogResult.OK)
            {
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString))
                {

                    string sqlStmt = string.Format("backup database Test_DB to disk='{0}'", sd.FileName);
                    using (SqlCommand bu2 = new SqlCommand(sqlStmt, conn))
                    {
                        conn.Open();
                        bu2.ExecuteNonQuery();
                        conn.Close();

                        DevComponents.DotNetBar.MessageBoxEx.Show("Backup Created Sucessfully");
                    }

                }
            }
        }

        catch (Exception)
        {
            MessageBox.Show("Backup Not Created");
        }
 // Restore backup Code


        try
        {
            OpenFileDialog od = new OpenFileDialog();
            od.Filter = "SQL Server database Restore files|*.bak";
            od.Title = "Restore Database Backup";


            if (od.ShowDialog() == DialogResult.OK)
            {
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString))
                {
                        string sqlStmt = string.Format("Restore database Test_DB from disk='{0}'", od.FileName);
                        using (SqlCommand bu2 = new SqlCommand(sqlStmt, conn))
                        {
                            conn.Open();
                            bu2.ExecuteNonQuery();
                            conn.Close();
                            DevComponents.DotNetBar.MessageBoxEx.Show("Database Retored Sucessfully", "Success Message!");
                        }

                }
            }
        }

        catch (Exception)
        {
            MessageBox.Show("Database didn't Restore","Error Message!");
        }

I appreciate any help provided by any body. thanks.

2 Answers
Related