如何在不使用 .mdf 或 .ldf 文件的情况下使用 C# 以编程方式将 .bak 文件还原到新服务器?

How can I restore a .bak file to a new server without using the .mdf or .ldf files, programmatically with C#?

一些入门信息:

  1. 我正在使用 SQL Server Express 2014
  2. 我正在使用 C#
  3. 我无法使用 SMO 功能完成以下任务

我正在尝试将从计算机 A 获得的 .bak 文件还原到计算机 B。 我想使用 C# 以编程方式执行此操作,但不使用 SMO 函数。

在 SSMS (SQL Server Management Studio) 中,我只需一个 .bak 文件即可手动恢复数据库。我希望能够使用 C# 执行相同的操作 运行ning 程序。

只要我有 .mdf 和 .ldf 文件,我就可以恢复 .bak 文件,但没有它们就不行。在 SSMS 中手动执行此操作似乎可行,因此我认为也必须有一种方法可以使用 C# 执行此操作。这是我拥有的:

DBConnection connect1 = new DBConnection();
connect1.connectionString = "Data Source=" + textBox1.Text + "; Integrated Security=SSPI"; // textbox1 contains a user entered server name.

// Create a new database.
using (SqlConnection myConnection = new SqlConnection(connect1.connectionString))// set the connection to sql.
{
    SqlCommand createDB = new SqlCommand("Create Database [" + dbName + "]", myConnection);
    createDB.Connection.Open();
    createDB.ExecuteNonQuery();
}

// Restore the data from the backup into the new database.
connect1 = new DBConnection();
connect1.connectionString = "Data Source=" + textBox1.Text + "; Initial Catalog=Master; Integrated Security=SSPI";
using (SqlConnection myConnection = new SqlConnection(connect1.connectionString))// set the connection to sql.
{
    //SqlCommand createDB = new SqlCommand("Restore Database [" + dbName + "] FROM DISK = " + bakDirctory + " "
    //    + "WITH MOVE '" + oldDBName + "' TO '" + mdfDirectory + "', "
    //    + "MOVE '" + oldDBName + "_log' TO '" + ldfDirectory + "', "
    //    + "REPLACE", myConnection);
    // oldDBName contains what the name of the database was when the .bak file was created.

    SqlCommand createDB = new SqlCommand("Restore Database [" + dbName + "] FROM DISK = " + bakDirectory, myConnection);
    createDB.Connection.Open();
    createDB.ExecuteNonQuery();
}

代码片段的注释部分有效,但需要使用 .mdf 和 .ldf 文件。下面的部分仅使用 .bak 文件,但在尝试 运行 该代码时出现未处理的异常:

备份集包含现有 'dbname' 数据库以外的数据库备份

我认为这是因为新创建的数据库的数据库结构与.bak 文件中的数据库结构不匹配。 (如果我说错了,请纠正我)。有没有办法只使用 .bak 文件恢复备份?预先感谢您抽出宝贵时间查看此内容。

如@DanGuzman 所述,无需事先创建新数据库。

按照 (@ScottChamberlain) 在评论中的说明,我能够在不使用 .mdf 或 .ldf 文件的情况下找到恢复数据库所需的脚本。确切的脚本是:

SqlCommand createDB = new SqlCommand("RESTORE DATABASE [" + dbName + "] FROM  DISK = N'" + bakDirectory + "' " +
"WITH  FILE = 2,  MOVE N'" + oldDBName + "' TO N'C:\Program Files\Microsoft SQL Server\MSSQL12.ANTSQLSERVER\MSSQL\DATA\" + dbName + ".mdf',  " +
"MOVE N'" + oldDBName + "_log' TO N'C:\Program Files\Microsoft SQL Server\MSSQL12.ANTSQLSERVER\MSSQL\DATA\" + dbName + "_log.ldf',  NOUNLOAD,  STATS = 5", myConnection);

(C:\Program Files\Microsoft SQL Server\MSSQL12.ANTSQLSERVER\MSSQL\DATA\) 路径是创建 .mdf 和 .ldf 文件的默认位置。