اول دستور
SqlClient.SqlConnection.ClearAllPools();
را اجرا کنید بعد کد detach را
SqlClient.SqlConnection.ClearAllPools();
SqlConnection1.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename='';Integrated Security=True;Connect Timeout=30;"'User Instance=True";
SqlCommand1.Connection.Open();
SqlCommand1.CommandType = CommandType.StoredProcedure;
SqlCommand1.CommandText = "sp_detach_db";
SqlCommand1.Parameters.AddWithValue("@dbname", SqlDbType.NVarChar).Value = FileIO.FileSystem.CurrentDirectory.ToString() + "\file.mdf";
SqlCommand1.Parameters.AddWithValue("@skipchecks", SqlDbType.NVarChar).Value = "true";
SqlCommand1.Parameters.AddWithValue("@keepfulltextindexfile", SqlDbType.VarChar).Value = "true";
SqlCommand1.ExecuteNonQuery();
SqlConnection1.Close();