title: smo restore database
body: <p>I use SQL Server SMO to restore a .bak to a new database, but failed to work. </p>
  
  <p>sql server is 2012 and smo object version is from the latest sdk version 11.0</p>
  
  <p>file .bak was created using sql management studio 2012, same local pc, on the same coding pc as well.</p>
  
  <p>The error message I get is:</p>
  
  <blockquote>
    <p>Restore failed for Server 'SERVER'.</p>
  </blockquote>
  
  <p>What's wrong with my code?</p>
  
  <pre><code>string dbPath = Path.Combine(@"d:\my data", dbName + "_db" + ".mdf");
  string logPath = Path.Combine(@"d:\my data", dbName + "_db" + "_Log.ldf");
  
  Restore restore = new Restore();
  
  BackupDeviceItem deviceItem = new BackupDeviceItem("d:\template.BAK", DeviceType.File);
  restore.Devices.Add(deviceItem);
  restore.Database = dbName + "_db";
  
  RelocateFile relocateDataFile = new RelocateFile("Data", dbPath);
  RelocateFile relocateLogFile = new RelocateFile("Log", logPath);
  
  restore.RelocateFiles.Add(relocateDataFile);
  restore.RelocateFiles.Add(relocateLogFile);
  
  restore.Action = RestoreActionType.Database;
  restore.ReplaceDatabase = true;
  restore.SqlRestore(server);
  </code></pre>
  
  <p>UPDATED: I surrended SMO solutions, and tried </p>
  
  <pre><code> using (SqlConnection connection = new SqlConnection("Data Source=server;user id=sa;password=xxxxx;"))
          {
  
              using (SqlCommand command = new SqlCommand(@"RESTORE DATABASE beauty01 FROM DISK = 'd:\template.bak' WITH RECOVERY, MOVE 'beauty1' TO 'D:\MyData\beauty01_Data.mdf', MOVE 'beauty1_log' TO 'd:\Mydata\beauty01_Log.ldf', REPLACE", connection))
              {
                  connection.Open();
                  // Add the parameters for the SelectCommand.
  
  
                  command.CommandType = CommandType.Text;
                  command.ExecuteNonQuery();
              }
  
          }  &gt;&gt; work good.
  </code></pre>
  
  <p>Thanks all.</p>