I define every factor Already which code is 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");
}

After I use string sql in SQL Sserver with new query I do not have problem and my database reinstates effectively however when I personally use this code with c# I check this out error

Error : being used with this session. It is suggested the master database be utilized when carrying out this operation. RESTORE DATABASE is terminating abnormally.

I wish to restore my database. I must open connection in the to begin my codes so when I wish to restore my database Exception.

Now how do i restore my database? Help Me.

You cannot restore the precise database you have attached to. Because the error message mentions, you need to use the master database rather.

Inside your connections string use database=master.

You have to be connected to another database compared to one you are attempting to revive. Set another database (inital catalog) in your soul connection string, connect, then run the code.

See how to restore sql-server database Through C# code for the similar problem.

However , you connection string has been initialized with Initial Catalog (or Database) set towards the database that you would like to revive. This will cause an association to become active (you should check this by performing sp_who2 system saved procedure) thus barring you to definitely do restore. You need to set your Initial Catalog (or Database) value inside a connection string to understand database. This will leave your target database free of connections and will help you to perform the restore process.

Look into the connection string. Whether it consists of a preliminary Catalog setting place it to understand.