如何在 C# 中恢复 SQL Server 2012 数据库 .bak 文件?

How to restore a SQL Server 2012 database .bak file in C#?

我开发了一个 Windows 表单的 MIS,我在其中备份了我的 SQL Server 2012 数据库,但我无法恢复备份 (.bak) 文件。

这是我的代码:

private void buttonRestore_Click(object sender, EventArgs e)
{
    try
    {
        openFileDialog1.Filter = "Backup File |*.bak";

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string sql = "Alter Database BOQ SET SINGLE_USER WITH ROLLBACK IMMEDIATE;";
            sql += "Restore Database BOQ FROM DISK ='" + openFileDialog1.FileName + "' WITH REPLACE;";

            SqlConnection con = new SqlConnection("Data Source=.; Initial Catalog=BOQ;Integrated Security=True");
            SqlCommand command = new SqlCommand(sql,con);

            con.Open();
            command.ExecuteNonQuery();

            MessageBox.Show("Database Recovered Successfully!");
            con.Close();
            con.Dispose();
        }
    }
    catch (Exception ex) 
    { 
         MessageBox.Show(ex.Message); 
    }
}

但是我得到这个错误:

无法连接到您的数据库BOQ,然后在其之上恢复.bak

"Data Source=.; Initial Catalog=BOQ;Integrated Security=True"
                                ****

您需要连接到 master 数据库,然后 您可以恢复您的 BOQ 数据库:

"Data Source=.; Initial Catalog=master;Integrated Security=True"
                                *******