Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem In Restore Database In C#

I define every thing Already and this code is a part of my code

if (Sql_Conn == null)
    Sql_Conn = new SqlConnection(Str_Con);
// str_con is my connection string

if (Sql_Conn.State != ConnectionState.Open)
   Sql_Conn.Open();

Data_Table = new DataTable();
DataA_dapter = new SqlDataAdapter();

Sql_Cmd = new SqlCommand();
Sql_Cmd.Connection = Sql_Conn; // 

string sql = "RESTORE DATABASE  [" + str_directory + "] From DISK = " +
                        "'" + strFileName + "' ; ";
// str_directory is the source of my database as DB.MDF
// srtFileName is the directory of DB.bak
Sql_Cmd.CommandType = CommandType.Text;
Sql_Cmd.CommandText = sql;

try
{
    Sql_Cmd.ExecuteNonQuery();
}
catch (SqlException Error_Exception)
{
   MessageBox.Show("Error");
}

When I use string sql in SQL Sserver with new query I don't have problem and my database restores successfully but when I use this code with c# I see this error

Error : {System.Data.SqlClient.SqlException: RESTORE cannot process database 'E:/DB.mdf' 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.

I want to restore my database. I have to open connection at the first of my codes and when I want to restore my database I see Exception.

Now how can I restore my database? Please Help Me.

like image 345
Masoud Abasian Avatar asked May 26 '26 04:05

Masoud Abasian


1 Answers

You can't restore the exact database that you have connected to. As the error message mentions, you should use the master database instead.

In your connections string use database=master.

like image 132
Guffa Avatar answered May 27 '26 18:05

Guffa