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.
Check the connection string. If it contains an Initial Catalog setting set it to Master.