title: How to restore SQL Server database backup to a newly created database?
body: <p>I've a SQL Server 2005 database backup named <code>backupdb.bak</code>.I  want to restore it to database <code>MyDatabase</code>.</p>
  
  <p>But before restoring I've to check whether <code>MyDatabase</code> already exists or not. If it does then I create a new database named <code>MyDatabaseNew</code> and I restore the backup file to this new database.</p>
  
  <p>If I'm directly restoring the file into <code>MyDatabase</code>, the process is running fine. But when I'm checking the existence of <code>MyDatabase</code> and trying to create new database named <code>MyDatabaseNew</code>, it's giving error:</p>
  
  <blockquote>
    <p>Restore failed for Server servername</p>
  </blockquote>
  
  <p>My code looks like this:</p>
  
  <pre><code>Restore restore = new Restore();
  restore.Action = RestoreActionType.Database;
  CreateDatabase(MyDatabaseNew);
  restore.Database = MyDatabaseNew;
  restore.ReplaceDatabase = true;
  
  BackupDeviceItem deviceItem = new BackupDeviceItem("C:\\backupdb.bak",DeviceType.File);
  restore.Devices.Add(deviceItem);
  SqlConnection sqlCon = new SqlConnection("Data Source=.;Initial Catalog=MyDatabaseNewIntegrated Security=True;User ID=uid; Pwd=Pwd");
  ServerConnection connection = new ServerConnection(sqlCon);
  sqlCon.Open();
  
  Microsoft.SqlServer.Management.Smo.Server smoServer = new Server(new  ServerConnection("."));
  if (File.Exists("C:\\backupdb.bak"))
      // restore
      restore.SqlRestore(smoServer);
  if (sqlCon.State == ConnectionState.Open)
      sqlCon.Close();
  </code></pre>
  
  <p>and my create database (in case <code>MyDatabase</code> exists) code looks like this, where I'm passing <code>MyDatabaseNew</code> as a parameter for this method:</p>
  
  <pre><code>public void CreateDatabase(string NewDBName)
  {
    string str;
    SqlConnection myConn = new SqlConnection("Server=.;Integrated  security=True;
    database=master;User ID=uid;Password=Pwd");
  
    str = "CREATE DATABASE " + NewDBName + "";
    SqlCommand myCommand = new SqlCommand(str, myConn);
    try
    {
      myConn.Open();
      myCommand.ExecuteNonQuery();
      MessageBox.Show("New DataBase is Created Successfully", "Database Creation",
      MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    catch (System.Exception ex)
    {
      MessageBox.Show(ex.ToString(), "Database Creation", MessageBoxButtons.OK,
      MessageBoxIcon.Information);
    }
    finally
    {
      if (myConn.State == ConnectionState.Open)
      {
        myConn.Close();
      }
    }
  }
  </code></pre>
  
  <p>Can any one tell me where I'm going wrong?</p>